TypeScript永远不会在条件类型中不一致地匹配类型?

时间:2018-12-31 07:13:58

标签: typescript

在下面的代码中,您注意到Result1的类型为never,而test3的类型为[]。我无法理解这一点。考虑到它们都从never读取MyEvents类型,为什么结果不一样?

type EventArgs<EventTypes, K extends keyof EventTypes> =
    EventTypes[K] extends never /* CHECK NEVER */
        ? []
        : EventTypes[K] extends any[]
            ? EventTypes[K]
            : [EventTypes[K]];

type foo<T> = T extends never /* CHECK NEVER */ ? [] : [boolean]
type Result1 = foo<MyEvents['anotherEvent']> // HERE, type is `never`

type MyEvents = {
    anotherEvent: never // event has no args
}

type Result2 = EventArgs<MyEvents, 'anotherEvent'> // HERE, type is `[]`

playground link

1 个答案:

答案 0 :(得分:2)

您真正要问的是:

type Foo = never extends never ? true : false // gives true
//but
type Bar<T> = T extends never ? true : false
type Baz = Bar<never> // not `true` as expected but `never`!

好吧,我对此感到好奇,想知道这是否与distributive conditional types有关。

所以我将上面的代码更改为此:

type Bar<T> = [T] extends [never] ? true : false
type Baz = Bar<never> // true as expected

因此,答案是:您正在分配一个空联合(又名never),这给出了一个空联合(又名never)的分配结果:那就是另一个空联合!完全有道理!

UPD:为什么never是“空联盟”?好吧,也许这段代码可以证明这一点:

type Union1 = number | string | never // number | string
type Union2 = number | never // number
type Union3 = never // never aka empty union