当我构建redux应用程序时收到警告消息:
“消息”:“类型'{ type: string;有效载荷: Text[];}‘不能分配到键入’MessageAction‘。\n类型的属性’类型‘是不兼容的。\n类型'string’不能分配到键入‘\”MESSAGES_ACTIONS_SUCCESS\’‘。“
所以:
在src/page/home/模块/类型中,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
发布于 2019-09-05 03:22:42
我重写了您提供的代码,以创建一个稍微简单一些的失败案例:
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更新了第一行,则应解决此键入问题:
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)。
https://stackoverflow.com/questions/57797782
复制相似问题