Typescript类型,类似于记录,但创建联合类型

问题描述 投票:0回答:1

我想为以下代码创建类型别名:

type Foo = {alpha: string} | {beta: string}

我想创建一个如下创建类型的类型,其中我将上面的类型定义为Foo<'alpha' | 'beta', string>

type Foo<K, T> = ...

记录不是一个选项,因为以下是正确的:

Record<'alpha' | 'beta', string> === {
    alpha: string;
    beta: string;
}
typescript
1个回答
1
投票

解决方案是使用映射类型。考虑下面的代码:

type GenericFoo<KeyT extends PropertyKey, ValueT> = {
  [Key in KeyT]: { [Key2 in Key]: ValueT }
}[KeyT];

type Foo = GenericFoo<'alpha' | 'beta', string>

[Foo被视为联合:

type Foo = {
    alpha: string;
} | {
    beta: string;
}

© www.soinside.com 2019 - 2024. All rights reserved.