![](/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.