gpt4 book ai didi

typescript - 映射类型的交集

转载 作者:搜寻专家 更新时间:2023-10-30 21:03:06 26 4
gpt4 key购买 nike

考虑以下几点:

type Properties = {
foo: { n: number };
bar: { s: string };
baz: { b: boolean };
};

declare function retrieveValues<K extends keyof Properties>(add?: K[]): Pick<Properties, K>[K];

// what happens
const x: { n: number } | { s: string } = retrieveValues(['foo', 'bar']);

// what I'm really trying to express (type error)
const y: { n: number } & { s: string } = retrieveValues(['foo', 'bar']);

有没有办法得到Pick<Properties, K>的属性的交集? ?或者只是根据数组中相关字符串的存在来获取一组类型的交集的不同方法?

最佳答案

使用 conditional typestype inference in conditional types可以转换 { n: number } | { s: string } 直接进入 { n: number } & { s: string }

type GetKeys<U> = U extends Record<infer K, any> ? K : never

type UnionToIntersection<U extends object> = {
[K in GetKeys<U>]: U extends Record<K, infer T> ? T : never
}

type Transformed = UnionToIntersection<{ a: string } | { b: number }>
// Transformed has type {a: string, b: number}

Playground Link

之所以可行,主要是因为条件类型分布在联合类型上。来自conditional types pull request :

Conditional types in which the checked type is a naked type parameter are called distributive conditional types. Distributive conditional types are automatically distributed over union types during instantiation. For example, an instantiation of T extends U ? X : Y with the type argument A | B | C for T is resolved as (A extends U ? X : Y) | (B extends U ? X : Y) | (C extends U ? X : Y).

关于typescript - 映射类型的交集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47464913/

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