在Typescript中,如何理解联合类型的'extends'?
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 不是 'never'?
在这种情况下 'extends' 做什么?
将您的 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
// --------------------------------------------------------------------------^^^^^
所以,现在 return 到你原来的案例
type isExtends<T, U> = T extends U ? T : never;
type Res2 = isExtends<"123" | "1234" | "12345", "123" | "1234">;
它导致 "123" | "1234"
因为它实际上是 ("123" | "1234") | never
这个
isExtends<"123" | "1234" | "12345", "123" | "1234">
可以展开为:
isExtends<"123" | "1234", "123" | "1234"> | isExtends("12345", "123" | "1234")
也就是
("123" | "1234") | never
简直就是
"123" | "1234"
这是我的尝试:
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 不是 'never'?
在这种情况下 'extends' 做什么?
将您的 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
// --------------------------------------------------------------------------^^^^^
所以,现在 return 到你原来的案例
type isExtends<T, U> = T extends U ? T : never;
type Res2 = isExtends<"123" | "1234" | "12345", "123" | "1234">;
它导致 "123" | "1234"
因为它实际上是 ("123" | "1234") | never
这个
isExtends<"123" | "1234" | "12345", "123" | "1234">
可以展开为:
isExtends<"123" | "1234", "123" | "1234"> | isExtends("12345", "123" | "1234")
也就是
("123" | "1234") | never
简直就是
"123" | "1234"