我可以在打字稿中用一个符号作为记录键吗



我想在typescript中使用一个符号作为对象键,但当我尝试以下代码时

class Item
{
key = Symbol('item');
}
const startingItem = new Item();
const items: Record<Item['key'], Item> = { [startingItem.key]: startingItem };
const item = items[startingItem.key];

我得到以下关于不能使用符号作为索引的错误

Element implicitly has an 'any' type because expression of type 'symbol' can't be used to index type 'Record<symbol, Item>'

Record实用程序类型的提示显示type Record<K extends string | number | symbol, T> = { [P in K]: T; },所以我不确定为什么会出现错误,因为这似乎是可能的?

此代码有效,但它适用于您的情况吗?

class Item
{
static readonly key: unique symbol = Symbol('item');
}
const startingItem = new Item();
const items: Record<typeof Item.key, Item> = { [Item.key]: startingItem };
const item = items[Item.key];

游乐场

相关内容

最新更新