typescript - 类型:类型变量与类型:字符串
问题描述
当我构建 react redux 应用程序时收到警告消息:
"message": "Type '{ type: string; payload: Text[]; }' 不可分配给类型 '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
解决方案
我重写了您提供的代码以创建一个稍微简单的失败案例:
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"'
问题是在这个例子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;
const
断言是在 TypeScript 3.4 中添加的,你可以在这里阅读更多关于它们的信息。突出显示的第一个问题是您遇到的问题:
不应该扩大该表达式中的文字类型(例如,不要从“hello”变为字符串)
推荐阅读
- qemu - Qemu Image Convert 在 Debian 启动时花费的时间太长
- ios - 如何通过在 Swift 5 中按下按钮来为图像设置动画。(OOP)
- python - Python pyats 和丰富的模块
- javafx - VBox 内的 TextArea 不垂直缩放
- php - fopen() 无法读取/写入 Mac Big Sur
- ios - 在 iOS 应用程序中阻止对非白名单域的 http/https 请求(主要来自 3rd 方库)
- javascript - 谷歌工作表脚本 - 将数组复制到范围的最后一行
- spring-boot - 如何以不同的方式呈现 ResponseEntity<>(HttpStatus.NOT_FOUND)?
- sql - R - 在 Oracle SQL 查询中使用 R 代码作为字符串
- c++ - VS2008 使用 CRT 堆调试 - CRTDBG 重载 new 和 CERN Root 重载 new 之间的冲突