为什么在这种情况下TypeScript类型推断会失败?

时间:2020-02-11 06:19:18

标签: typescript types

我想了解为什么类型S1never,但是当我删除labelcustomRef属性时,我得到了正确的string结果。当我删除valuelabel属性时,我得到unknown

export interface BaseInputProps<TStored> {
  value: TStored;
  customRef?: (selfProps: this) => void;
}

export interface TestInput extends BaseInputProps<string> {
  label: string;
}

type InferStoredType<T> = T extends BaseInputProps<infer TT> ? TT : never;

type S1 = InferStoredType<TestInput>;

这是怎么回事?

打字稿版本3.7.5。在Typescript游乐场上以相同的方式工作。

1 个答案:

答案 0 :(得分:2)

这与结构差异和weak type有关。因此,让我们了解所有情况下的问题

情况1:默认情况下,永远不会

当您尝试将interface TestInput扩展为interface BaseInputProps<string>时,它将 尝试检查所有键入的属性是否兼容,但是在这种情况下,customRef?: (selfProps: this) => void;类型(selfProps: this)=> void无法分配给string,反之亦然。这就是为什么它是虚假继承的原因,因为S1是never

情况2:删除标签和customRef时,它是字符串

删除标签后,customRef interface BaseInputPropsinterface TestInput将被保留一个强制性属性value,因为它会正确地推断出类型。

情况3:删除值和标签时,它是未知的

删除值并标记interface BaseInputProps后, interface TestInput将只保留可选属性,而 在这种情况下,打字稿不能保证打字。

仍然,为什么要有意进行此更改是一个问题。但是,从规格变化的范围来看,我想很难看到变化。

weak typingconditional typings上也请阅读更多内容。

相关问题