[英]In Typescript, how to understand 'extends' of union types?
這是我的嘗試:
type Comb1 = "123" | "1234";
type Comb2 = "123" | "1234" | "12345";
type Res<T, U> = T extends U ? T : never;
// Res1 === "123" | "1234"
type Res1 = isExtends<Comb1, Comb2>;
// Res2 === "123" | "1234"
type Res2 = isExtends<Comb2, Comb1>;
為什么 Res2 不是“從不”?
在這種情況下,“擴展”做什么?
將您的isExtends
類型更改為:
type isExtends<T, U> = T extends U ? 1 : 0;
然后你會看到:
type Res1 = isExtends<"123" | "1234", "123" | "1234" | "12345">; // Res1 === 1
type Res2 = isExtends<"123" | "1234" | "12345", "123" | "1234">; // Res2 === 0 | 1
// --------------------------------------------------------------------------^^^^^
所以,現在回到你原來的情況
type isExtends<T, U> = T extends U ? T : never;
type Res2 = isExtends<"123" | "1234" | "12345", "123" | "1234">;
結果是"123" | "1234"
"123" | "1234"
因為它是事實上的("123" | "1234") | never
("123" | "1234") | never
這個
isExtends<"123" | "1234" | "12345", "123" | "1234">
可以展開為:
isExtends<"123" | "1234", "123" | "1234"> | isExtends("12345", "123" | "1234")
這是
("123" | "1234") | never
這很簡單
"123" | "1234"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.