![](/img/trans.png)
[英]Why can't TypeScript infer a generic type when it is in a nested object?
[英]Why can't Typescript infer prop type when using Generics?
在下面的代碼中:
interface MyInterface {
a: {
b: {
c: "c";
};
};
}
type ParentProps = keyof MyInterface
type ChildProps<ParentProp extends ParentProps> = keyof MyInterface[ParentProp]
type GrandChildType<ParentProp extends ParentProps, ChildProp extends ChildProps<ParentProp>> =
MyInterface[ParentProp][ChildProp]['c']
我在GrandChildType
中收到錯誤消息:
類型“c”不能用於索引類型“MyInterface[ParentProp][ChildProp]”。(2536)
但是,如果我將最后一行更改為:
type GrandChildType<ParentProp extends ParentProps, ChildProp extends ChildProps<ParentProp>> =
MyInterface[ParentProp][ChildProp]
type test = GrandChildType<'a', 'b'>['c']
然后我正確地得到c
的類型,即"c"
。 所以,問題是:如果ParentProps
和ChildProps
都是從MyInterface
中提取的鍵,為什么我在使用 Generics 時無法獲得該值類型?
可復制鏈接: typescript playground
這似乎是 TypeScript 中的一個錯誤; 有關詳細信息,請參閱Microsoft/TypeScript#27709 。 嵌套的通用索引訪問類型似乎“忘記”了它們的約束,並且不再讓您使用特定鍵對它們進行索引。 該錯誤已經存在很長時間了,沒有跡象表明它會很快得到解決,因此您可能想要解決它。
如果您的類型T
知道T extends U
為真但編譯器不知道,您通常可以使用Extract<T, U>
實用程序類型將T
替換為Extract<T, U>
<T, U> 。 編譯器將接受Extract<T, U> extends U
,並假設您對T extends U
的看法是正確的,然后最終(當指定 generics 時), Extract<T, U>
將僅評估為T
。 (請注意,這是Extract<T, U>
的“標簽外”使用,主要用於將T
中的聯合過濾為僅可分配給U
的那些成員。)
為了使用鍵類型"c"
索引到某個類型T
,這意味着該類型應該可以分配給{c?: any}
。 如果T["c"]
編譯失敗,那么Extract<T, {c?: any}>
應該會成功。 讓我們在這里試試:
type GrandChildType<K extends keyof MyInterface, K2 extends keyof MyInterface[K]> =
Extract<MyInterface[K][K2], { c?: any }>['c']; // okay
type C = GrandChildType<"a", "b"> // "c"
看起來挺好的! GrandChildType<"a", "b">
的類型按要求是"c"
, GrandChildType
的錯誤就沒有了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.