typescript - 打字稿中的扩展运算符剥离类型定义
问题描述
我在打字稿中遇到了这种奇怪的现象。使用扩展运算符时,类型检查似乎丢失了。我希望这会引发错误:
interface Input {
thingOne: string;
thingTwo: number;
thingThree: string;
thingFour: boolean;
thingFive: Array<number>
}
interface Output {
thingThree: string;
thingFour: boolean;
thingFive: Array<number>
}
const transformFunction = (input: Input): Output => {
const result: Output = {
...input,
thingFour: !input.thingFour
}
return result
}
打字稿游乐场示例
我正在键入result
as Output
,但将类型对象传播Input
到其中显然会产生不属于该类型的结果Output
。为什么打字稿没有捕捉到这个?
解决方案
我们在这里期望的是触发TypeScript 的Excess Property Check功能。这个特性告诉我们,如果我们明确提到对象类型,TypeScript 会警告我们对象中是否有额外的属性。不幸的是,它仅适用于对象文字。
例如这个:
const transformFunction = (input: Input): Output => {
return {
thingOne: "string;",
thingTwo: 123,
thingThree: "string;",
thingFour: !input.thingFour,
thingFive: [1, 23],
};
};
警告:
Type '{ thingOne: string; thingTwo: number; thingThree: string; thingFour: boolean; thingFive: number[]; }' is not assignable to type 'Output'.
Object literal may only specify known properties, and 'thingOne' does not exist in type 'Output'.
似乎扩展运算符的情况不在额外的属性检查范围内。见这里:https ://github.com/microsoft/TypeScript/issues/41237
这是多余的属性检查。根据@RyanCavanaugh 的说法,它更像是一个 linter,而不是类型系统的一部分。但正如您所注意到的,并非所有情况都包含在此检查中。
他们还提到在此处研究确切类型的持续转换:https ://github.com/microsoft/TypeScript/issues/12936
推荐阅读
- swift - 如何在嵌套循环中访问变量?
- c++ - 使用 Excel VBA 中的 C++ dll 时出现“错误的 DLL 调用约定” - 如何解决?
- java - 自定义 JPasswordField 中的高 CPU 使用率
- mongodb - 使用 Mongoose 时的 MongoDB 弃用警告
- facebook-marketing-api - 消息“应用程序没有能力进行此 API 调用。” 在 API '/adcreative'
- java - maven 项目无法执行“maven-thrift-plugin”
- authentication - 主要的第一方移动应用程序如何确保其登录流程只能在其应用程序内完成?
- python - 如何用我自己的函数初始化 pytorch 中的权重?(cs231n PyTorch 笔记本)
- c - “删除事件”信号的回调函数传递了不正确的变量值
- angularjs - 单击链接时Angularjs ui-view路由不起作用