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

时间:2021-03-28 15:11:50

标签: 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; },所以我不确定为什么我会收到错误,因为这似乎应该是可能的?

1 个答案:

答案 0 :(得分:2)

此代码有效,但对您的情况有效吗?

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];

Playground

相关问题