我想了解为什么类型S1
是never
,但是当我删除label
或customRef
属性时,我得到了正确的string
结果。当我删除value
和label
属性时,我得到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游乐场上以相同的方式工作。
答案 0 :(得分:2)
这与结构差异和weak type有关。因此,让我们了解所有情况下的问题
情况1:默认情况下,永远不会
当您尝试将
interface TestInput
扩展为interface BaseInputProps<string>
时,它将 尝试检查所有键入的属性是否兼容,但是在这种情况下,customRef?: (selfProps: this) => void;
类型(selfProps: this)=> void
无法分配给string
,反之亦然。这就是为什么它是虚假继承的原因,因为S1是never
情况2:删除标签和customRef时,它是字符串
删除标签后,customRef
interface BaseInputProps
和interface TestInput
将被保留一个强制性属性value
,因为它会正确地推断出类型。
情况3:删除值和标签时,它是未知的
删除值并标记
interface BaseInputProps
后,interface TestInput
将只保留可选属性,而 在这种情况下,打字稿不能保证打字。
仍然,为什么要有意进行此更改是一个问题。但是,从规格变化的范围来看,我想很难看到变化。
在weak typing和conditional typings上也请阅读更多内容。