类型:typeof变量与类型:字符串

时间:2019-09-05 02:46:20

标签: typescript

在构建React Redux应用程序时得到警告消息:

  

“ message”:“类型'{类型:字符串;有效载荷:文本[];}'无法分配给类型'MessageAction'。\ n属性'type'的类型不兼容。\ n类型'string'是不能分配给'\“ MESSAGES_ACTIONS_SUCCESS \”''。”,

所以:

src / pages / home / modules / types.ts中的1和2有什么区别

// 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[]
}
// 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

1 个答案:

答案 0 :(得分:1)

我重写了您提供的代码以创建稍微简单的故障案例:

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"'

Here is the TypeScript playground

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

如果您用as const更新了第一行,应该可以解决此键入问题:

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;

Here is the TypeScript playground for the fixed example

在TypeScript 3.4和you can read more here about them中添加了

const断言。突出显示的第一个问题是您遇到的问题:

  

该表达式中的所有文字类型都不应扩展(例如,不要从“ hello”到字符串)