MrY*_*Dao 2 typescript typescript-generics typescript-typings
假设我有一个字符串列表
const arr = ["a", "b", "c"];
Run Code Online (Sandbox Code Playgroud)
我究竟如何将其转换为对象,以使这些值成为任何对象的键?
const obj = {
a: "can be anything",
b: 2,
c: 0
}
Run Code Online (Sandbox Code Playgroud)
我尝试过使用
type TupleToObject<T extends readonly string[]> = {
[P in T[number]]: any;
};
Run Code Online (Sandbox Code Playgroud)
但它似乎不是强类型的。
您可以使用as constTypeScript 语法(请参阅文档)。
const arr = ["a", "b", "c"] as const;
// inferred type: readonly ["a", "b", "c"]
type TupleToObject<T extends readonly string[]> = {
[P in T[number]]: any;
};
type MyObject = TupleToObject<typeof arr>
// type MyObject = {
// a: any;
// b: any;
// c: any;
// }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
717 次 |
| 最近记录: |