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

时间:2018-07-02 09:53:27

标签: javascript typescript interface

我有两个课:

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一样,因为在打字稿中

  

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

1 个答案:

答案 0 :(得分:2)

  

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

不,不包含对象文字。

但是,您可以改用Map

  

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

相关问题