[英]Why does TypeScript type inference fail in this case?
I want to understand why type S1
is never
, but when I remove the label
or customRef
properties I get correct result of string
.我想了解为什么类型
S1
never
,但是当我删除label
或customRef
属性时,我得到了string
正确结果。 When I remove the value
and label
properties I get unknown
.当我删除
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>;
What is happening here?这里发生了什么?
Typescript version 3.7.5.打字稿版本 3.7.5。 Works the same way on the Typescript playground.
在 Typescript 操场上的工作方式相同。
It has to do with the structural difference and weak type .它与结构差异和弱类型有关。 So let's understand your problem in all the cases
因此,让我们了解您在所有情况下的问题
Case 1: By default, it is never情况 1:默认情况下,从不
When you try to extend
interface TestInput
withinterface BaseInputProps<string>
it will try to check if all the properties typing are compatible but in this casecustomRef?: (selfProps: this) => void;
当您尝试使用
interface BaseInputProps<string>
扩展interface TestInput
时,它将尝试检查所有属性类型是否兼容,但在这种情况下customRef?: (selfProps: this) => void;
type(selfProps: this)=> void
is not assignable tostring
and vice versa.type
(selfProps: this)=> void
不能赋值给string
,反之亦然。 That's why it is falsy inheritance because of which S1 isnever
这就是为什么它是虚假继承的原因,因为 S1
never
Case 2: When you remove label and customRef, it is string情况二:去掉label和customRef,是string
When you removed label and customRef
interface BaseInputProps
andinterface TestInput
will be left out with one compulsory propertyvalue
because of which it will correctly infer the typings.当您删除 label 和 customRef
interface BaseInputProps
和interface TestInput
将被排除在一个强制属性value
,因此它将正确推断类型。
Case 3: When you remove value and label, it is unkown案例3:当你移除value和label时,它是未知的
When you removed the value and label
interface BaseInputProps
andinterface TestInput
will be left out with only optional property and typescript can't guarantee the typings in this case.当您删除值和标签时,
interface BaseInputProps
和interface TestInput
将被排除在外,只有可选属性,并且在这种情况下打字稿无法保证类型。
Still, why this change was intentional is a question.不过,为什么这种变化是有意的,这是一个问题。 But, looking at the scope of the spec change it will involve, I guess it's very difficult to see a change in this.
但是,看看它将涉及的规范更改的范围,我想很难看到这方面的变化。
Please read this too for more on weak typing and on conditional typings .请阅读本文以了解更多关于弱类型和条件类型的信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.