![](/img/trans.png)
[英]Why does method chaining in TypeScript cause generic type inference to fail?
[英]Why does TypeScript type inference fail in this case?
我想了解为什么类型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 操场上的工作方式相同。
它与结构差异和弱类型有关。 因此,让我们了解您在所有情况下的问题
情况 1:默认情况下,从不
当您尝试使用
interface BaseInputProps<string>
扩展interface TestInput
时,它将尝试检查所有属性类型是否兼容,但在这种情况下customRef?: (selfProps: this) => void;
type(selfProps: this)=> void
不能赋值给string
,反之亦然。 这就是为什么它是虚假继承的原因,因为 S1never
情况二:去掉label和customRef,是string
当您删除 label 和 customRef
interface BaseInputProps
和interface TestInput
将被排除在一个强制属性value
,因此它将正确推断类型。
案例3:当你移除value和label时,它是未知的
当您删除值和标签时,
interface BaseInputProps
和interface TestInput
将被排除在外,只有可选属性,并且在这种情况下打字稿无法保证类型。
不过,为什么这种变化是有意的,这是一个问题。 但是,看看它将涉及的规范更改的范围,我想很难看到这方面的变化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.