首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >类型:类型变量与类型: string

类型:类型变量与类型: string
EN

Stack Overflow用户
提问于 2019-09-05 02:46:20
回答 1查看 355关注 0票数 1

当我构建redux应用程序时收到警告消息:

“消息”:“类型'{ type: string;有效载荷: Text[];}‘不能分配到键入’MessageAction‘。\n类型的属性’类型‘是不兼容的。\n类型'string’不能分配到键入‘\”MESSAGES_ACTIONS_SUCCESS\’‘。“

所以:

在src/page/home/模块/类型中,1和2的不同是什么?

代码语言:javascript
复制
// src/pages/home/modules/types.ts
1. got warn msg
export const MESSAGES_ACTIONS_SUCCESS = "MESSAGES_ACTIONS_SUCCESS"

export interface MessageAction {
  type: typeof MESSAGES_ACTIONS_SUCCESS
  payload: Text[]
}

2.no warn msg
export const MESSAGES_ACTIONS_SUCCESS = "MESSAGES_ACTIONS_SUCCESS"

export interface MessageAction {
  type: string
  payload: Text[]
}
代码语言:javascript
复制
// src/pages/home/modules/actions.ts
import { Dispatch } from "redux"

import { MESSAGES_ACTIONS_SUCCESS, MessageAction } from "./types"

export const loadMessageData = () => async (
  dispatch: Dispatch
): Promise<MessageAction> => {
  const messages: Text[] = await new Promise(resolve => {
    setTimeout(() => resolve([{ text: "home ~~~~~~" }]))
  })

  return dispatch({
    type: MESSAGES_ACTIONS_SUCCESS,
    payload: messages
  })
}

更多信息代码回购是https://github.com/77xi/SSR/pull/5

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-09-05 03:22:42

我重写了您提供的代码,以创建一个稍微简单一些的失败案例:

代码语言:javascript
复制
const MESSAGES_ACTIONS_SUCCESS = "MESSAGES_ACTIONS_SUCCESS";

interface MessageActionOne {
  type: typeof MESSAGES_ACTIONS_SUCCESS;
  payload: Text[];
}

interface MessageActionTwo {
  type: string;
  payload: Text[];
}

// Infered type will be: { type: string; payload: never[]; }
const action = {
  type: MESSAGES_ACTIONS_SUCCESS,
  payload: []
};

const one: MessageActionOne = action;
//    ^^^  Type 'string' is not assignable to type '"MESSAGES_ACTIONS_SUCCESS"'

这里是TypeScript游乐场

问题是,在本例中,action被推断为type: string而不是type: "MESSAGES_ACTIONS_SUCCESS"

如果使用as const更新了第一行,则应解决此键入问题:

代码语言:javascript
复制
const MESSAGES_ACTIONS_SUCCESS = "MESSAGES_ACTIONS_SUCCESS" as const;

interface MessageActionOne {
  type: typeof MESSAGES_ACTIONS_SUCCESS;
  payload: Text[];
}

interface MessageActionTwo {
  type: string;
  payload: Text[];
}

// Infered type will be: { type: "MESSAGES_ACTIONS_SUCCESS"; payload: never[]; }
const action = {
  type: MESSAGES_ACTIONS_SUCCESS,
  payload: []
};

const one: MessageActionOne = action;

下面是这个固定示例的TypeScript游乐场

const断言是在TypeScript 3.4和你可以在这里读到更多关于他们的信息。中添加的。突出显示的第一个问题是您遇到的问题:

该表达式中的任何文字类型都不应加宽(例如,不能从"hello“到string)。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57797782

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档