我了解keyof运算符以及如何创建由该对象的键组成的联合类型,如下所示:
interface Foo {
a: string;
b: string;
}
type Goo = keyof Foo; // "a" | "b"
Run Code Online (Sandbox Code Playgroud)
我想做完全相反的事情,并从键的联合创建一个新的对象类型。
const MakeTuple = <T extends string[]>(...args: T) => args;
const Types = MakeTuple("A", "B", "C");
type TypeVariant = typeof Types[number];
type VariantObject = {
// This gives error consider using a mapped object but I'm not sure how to do that
[type: TypeVariant]: [boolean, boolean, boolean, string[]];
}
Run Code Online (Sandbox Code Playgroud)
所以我想要的是采用键的联合并生成一个类型,其中包含 type 的每个键的值[boolean, boolean, boolean, string[]]。
您可以只使用预定义的Record映射类型
const MakeTuple = <T extends string[]>(...args: T) => args;
const Types = MakeTuple("A", "B", "C");
type TypeVariant = typeof Types[number];
type VariantObject = Record< TypeVariant, [boolean, boolean, boolean, string[]] >
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1629 次 |
| 最近记录: |