【发布时间】:2019-08-27 18:26:35
【问题描述】:
在 TypeScript 中,是否可以将对象中的每个键作为泛型传递给该对象中的每个对应值?例如:
interface Items
{
[key: Key extends string]: Item <Key>;
};
interface Item <Key>
{
name: Key;
};
如果键是字符串字面量,这可以实现:
type Name = 'a' | 'b' | 'c';
type Items =
{
[Key in Name]?: Item<Key>;
};
interface Item <Name>
{
name: Name;
};
const items: Items =
{
// Type valid
a:
{
name: 'a'
},
// Type error
b:
{
name: 'c'
}
};
我不确定如何扩展它以允许任何字符串。任何帮助将不胜感激。
【问题讨论】:
标签: typescript