Cri*_*tos 0 types casting typescript
我有一个使用相同属性的常量对象数组。像这样的东西:
const allData = [{
name: 'info', content: Info
},{
name: 'other', content: Other
},{
...
}];
Run Code Online (Sandbox Code Playgroud)
现在我想创建一个变量,在运行其他一些代码后,该变量会将它们映射到一个对象中,其中键是name属性的字符串,值是content属性的实例。鉴于此,我想知道如何在 Typescript 中定义这样一个类型,它基本上会从我的常量中提取这些属性,最终会变成这样:
Type ContentInstances = {
info: Info,
other: Other
...
}
Run Code Online (Sandbox Code Playgroud)
有没有这样的方法使用 typeof 和 Typescript 上的其他东西来基于allData常量动态实现这一点?
编辑 基本上在稍后阶段,我会有这样的事情:
let myVar: ContentInstances;
...
myVar = allData.reduce((obj, value) => {
obj[value.name] = new value.content(customParam);
return obj;
}, {})
Run Code Online (Sandbox Code Playgroud)
以下应该可以解决问题:
const allData = [
{
name: "info",
content: { hey: "you" },
},
{
name: "other",
content: { bro: "chill" },
},
] as const;
type ContentInstances = {
[K in typeof allData[number]["name"]]: Extract<
typeof allData[number],
{ name: K }
>["content"];
};
declare const foo: ContentInstances;
foo.info.hey;
foo.other.bro;
Run Code Online (Sandbox Code Playgroud)
该类型ContentInstances迭代 中"name"包含的对象的所有键allData。它将每个键映射到具有该键的对象的联合中,然后用该"content"键对联合进行索引。