简体   繁体   English

定义选取键的并集类型

[英]Define a union type of picked keys

Given an interface, eg: 给定一个接口,例如:

interface A {
    AA : string
    AB : number
}

I would like a type that is a union of every possible picked type, eg: 我想要一个类型是所有可能选择的类型的并集,例如:

type B = Pick<A, "AA"> | Pick<A,"AB"> 

Or, if not familiar with Pick: 或者,如果不熟悉Pick:

type B = {AA: string} | {BB : number}

I don't want to have to write it out manually like above though. 我不想像上面那样手动将其写出。 I'd like to be able to write some kind of generic type or function that will do it for me, eg 我希望能够编写某种通用类型或函数来帮我,例如

type B = OneOf<A>

How would 'OneOf' be written, or what is the closest current approximation/workaround in typescript? 如何写“ OneOf”,或者打字稿中最接近的当前近似值/解决方法是什么?

How about something like this: 这样的事情怎么样:

type OneOf<T> = {[K in keyof T]: Pick<T, K>}[keyof T];

Using that structure, your example would look like this: 使用该结构,您的示例将如下所示:

interface A {
    AA: string;
    AB: number;
}

declare var x: OneOf<A>;

// x now has type:
// Pick<A, "AA"> | Pick<A, "AB">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM