【问题标题】:Is there any way in typescript to use objects as keys?打字稿中有什么方法可以将对象用作键吗?
【发布时间】:2018-07-02 09:53:27
【问题描述】:

我有两个班级:

class A {
  name: string;
  age: number;

  constructor(name: string, age: number) { 
      this.name = name;
      this.age = age;
  }
}

class B extends A {

}

我还有一个对象,我想将这些类的实例用作键:

const storage: Storage = {};

所以它看起来像这样:

const a = new A('Neo', 25);
const b = new A('Smith', 31);
storage[a] = 'What are you trying to tell me? That I can dodge bullets?';
storage[b] = 'Never send a human to do a machine's job.'

然后我想通过键来区分值,例如:

const keys = Object.keys(storage);
keys.forEach(key => {
  if (key instanceof A) {
    console.log('This is Neo');
  } else if (key instanceof B) {
    console.log('This is Smith');
  }
})

应该如何看起来像Storage 界面,因为在打字稿中

索引签名参数类型必须是“字符串”或“数字”

【问题讨论】:

  • 这个用例看起来只需要一个数组对就可以了,比如const storage: Array<[A, string]>storage.push([a, 'What are...']);。为什么需要通过对象索引storage?你能展示一个重要的用例吗?

标签: javascript typescript interface


【解决方案1】:

打字稿中有什么方法可以使用对象作为键吗?

不,不是对象字面量。

但是,您可以改用Map

Map 对象包含键值对。 任何值(对象和原始值)都可以用作键或值。

【讨论】:

  • 我如何为Map 指定接口,该接口应该用作AB 类的唯一实例?
  • 你可以用你自己的实现继承Map
  • TypeScript’s Map takes two type parameters,因此您可以指定键和值的类型:new Map<K, V>()
  • 您能否扩展“不使用对象文字”以帮助那些不熟悉使用Map 的潜在陷阱的人?也就是说,由于Map 使用对象标识来实现键相等,如果您使用对象作为键将值放入映射中,则只能使用 same object... 检索它...如果您曾经反序列化或克隆代码中的对象,请咬您一口。
  • @jcalz 不太清楚你的意思。如果您想了解更多关于Map 的信息,通常最好阅读 MDN 上的帖子和链接的规范。
猜你喜欢
  • 2021-05-01
  • 2017-06-29
  • 2017-02-26
  • 2021-12-11
  • 1970-01-01
  • 2018-05-31
  • 2020-04-20
  • 2012-11-09
  • 1970-01-01
相关资源
最近更新 更多