将联合映射到接口属性

是否可以将联合类型映射到 Typescript 中的接口?

我希望能够做什么

给定联合类型 A:

type A = 'one' | 'two' | 'three';

我希望能够将其映射到接口 B:

interface B {
    one:   boolean;
    two:   boolean;
    three: boolean;
}

回答

映射类型使这变得非常简单:

type A = 'one' | 'two' | 'three';

type B = {
    [property in A]: boolean;
};

B 最终是:

{
    one:   boolean;
    two:   boolean;
    three: boolean;
}

游乐场链接

但正如Aleksey L.指出的那样,有一个实用程序类型Record

type B = Record<A, boolean>;

使用映射类型,您甚至可以通过将条件类型放入混合中来使属性的类型不同:

type A = 'one' | 'two' | 'three';

type B = {
    [property in A]: property extends 'one' ? number : boolean;
};

B 最终是:

{
    one:   number;
    two:   boolean;
    three: boolean;
}

游乐场链接


以上是将联合映射到接口属性的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>