gpt4 book ai didi

typescript :如何解释扩展和函数类型之间的这种交互

转载 作者:搜寻专家 更新时间:2023-10-30 20:56:58 25 4
gpt4 key购买 nike

示例 1 对我来说非常有意义

type X = (1 | 2 | 3) extends (infer I) ? [I] : never;

// X = [1 | 2 | 3]

例子2 不知道为什么现在类型变量是相交的

type X = (
((_: 1) => void) | ((_: 2) => void) | ((_: 3) => void)
) extends ((_: infer I) => void) ? [I] : never;

// X = [1 & 2 & 3]

我的猜测是这与此有某种关系/相似之处:

type X = { x: number } | { y: number } | { z: number };
type Y = keyof X;

// Y = x & y & z

但是,我无法说服自己我从第一原则就理解了它。很想听听这是如何解释的。

最佳答案

type inference from conditional types 时的发行说明中对此进行了解释被介绍。它是并集还是交集取决于 variance的推断类型。直观上,如果一个类型被推断为多个值的公共(public)类型,则它可以是其中任何一个(联合),但如果它被推断为多个函数的参数类型,则它必须被其中任何一个接受(交集)。

引用发行说明:

The following example demonstrates how multiple candidates for the same type variable in co-variant positions causes a union type to be inferred:

type Foo<T> = T extends { a: infer U, b: infer U } ? U : never;
type T10 = Foo<{ a: string, b: string }>; // string
type T11 = Foo<{ a: string, b: number }>; // string | number

Likewise, multiple candidates for the same type variable in contra-variant positions causes an intersection type to be inferred:

type Bar<T> = T extends { a: (x: infer U) => void, b: (x: infer U) => void } ? U : never;
type T20 = Bar<{ a: (x: string) => void, b: (x: string) => void }>; // string
type T21 = Bar<{ a: (x: string) => void, b: (x: number) => void }>; // string & number

可以在 PR implementing 中找到更多讨论。这个功能。

作为旁注,它启用了一些很酷的技巧,例如 union to intersection type conversion .

关于 typescript :如何解释扩展和函数类型之间的这种交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54936474/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com