【问题标题】:In Typescript, how to understand 'extends' of union types?在 Typescript 中,如何理解联合类型的“扩展”?
【发布时间】:2020-12-01 07:25:25
【问题描述】:

这是我的尝试:

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 不是“从不”?

在这种情况下,“扩展”做什么?

【问题讨论】:

标签: typescript extends union-types


【解决方案1】:

将您的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") | never

这个

isExtends<"123" | "1234" | "12345", "123" | "1234">

可以扩展为:

isExtends<"123" | "1234", "123" | "1234"> | isExtends("12345", "123" | "1234")

这是

("123" | "1234") | never

这很简单

"123" | "1234"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-25
    • 1970-01-01
    • 1970-01-01
    • 2018-01-03
    • 2016-08-02
    • 2019-11-02
    • 1970-01-01
    相关资源
    最近更新 更多