【问题标题】:How to pick common properties from two types?如何从两种类型中选择共同的属性?
【发布时间】:2020-07-15 20:18:33
【问题描述】:

我想通过仅选择两种类型中都存在的成员来创建类型:

interface A {
    X: number;
    Y: number;
}
interface B {
    Y: number;
    Z: number;
}

type C = Common<A, B>; // { Y: number; }

是否有内置的实用程序类型、命题或常用模式来实现这一点?

注意:我能够编写以下实用程序类型,但我认为这很难推理

type Common<T1, T2> = Omit<T1, keyof Omit<T1, keyof T2>>

但是,有什么问题

【问题讨论】:

    标签: typescript typescript-generics


    【解决方案1】:

    您可能会发现这更容易阅读:

    type C = Pick<A | B, keyof A & keyof B>; // { Y: number; }
    

    它从 A 和 B (A | B) 的总和中挑选 (Pick) 共同属性 (keyof A &amp; keyof B)。

    【讨论】:

    • 嗯,这实际上可以简化为输入type C = Pick&lt;A, keyof A &amp; keyof B&gt;,对吧?
    • 甚至Pick&lt;A, keyof (A | B)&gt;?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-22
    • 2018-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多