首页 > 解决方案 > 打字稿中的扩展运算符剥离类型定义

问题描述

我在打字稿中遇到了这种奇怪的现象。使用扩展运算符时,类型检查似乎丢失了。我希望这会引发错误:

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
}

打字稿游乐场示例

我正在键入resultas Output,但将类型对象传播Input到其中显然会产生不属于该类型的结果Output。为什么打字稿没有捕捉到这个?

标签: typescript

解决方案


我们在这里期望的是触发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


推荐阅读