我想为以下代码创建类型别名:
type Foo = {alpha: string} | {beta: string}
Run Code Online (Sandbox Code Playgroud)
我想创建一个类型,如下所示,我将上面的类型定义为Foo<'alpha' | 'beta', string>
type Foo<K, T> = ...
Run Code Online (Sandbox Code Playgroud)
记录不是一个选项,因为以下内容为真:
Record<'alpha' | 'beta', string> === {
alpha: string;
beta: string;
}
Run Code Online (Sandbox Code Playgroud)
解决方案是使用映射类型。考虑下面的代码:
type GenericFoo<KeyT extends PropertyKey, ValueT> = {
[Key in KeyT]: { [Key2 in Key]: ValueT }
}[KeyT];
type Foo = GenericFoo<'alpha' | 'beta', string>
Run Code Online (Sandbox Code Playgroud)
Foo被评估为联合:
type Foo = {
alpha: string;
} | {
beta: string;
}
Run Code Online (Sandbox Code Playgroud)
一些解释:
GenericFoo创建一个映射类型,其值代表所有对{key,value}[KeyT]定义末尾GenericFoo意味着我们采用映射类型的所有值类型,这意味着我们得到所有对的并集{key,value}。| 归档时间: |
|
| 查看次数: |
4541 次 |
| 最近记录: |