javascript - typescript 中有什么方法可以使用对象作为键吗?

标签 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接口(interface),因为在 typescript 中

An index signature parameter type must be 'string' or 'number'

最佳答案

Is there any way in typescript to use objects as keys?

不,不能使用对象文字。

但是,您可以使用Map相反:

The Map object holds key-value pairs. Any value (both objects and primitive values) may be used as either a key or a value.

关于javascript - typescript 中有什么方法可以使用对象作为键吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51133422/

相关文章:

javascript - 当使用 contentType : 'application/json; charset=utf-8' , 时,我的数据不会传递给 api Controller

angular - RXJS 运算符(operator)不使用 firebase

angular - 如何将 Angular Material cdk 步进器与构造函数一起使用

java - 接口(interface) : Java Language Specification

java - 如何最好地测试 Java 代码?

c++ - C++中没有数据成员的类

javascript - 在没有 new 运算符的情况下使用 $resource 时出现问题

javascript - onbeforeUnload 不返回或不显示对话框

angularjs - 不同项目之间的Angular JS模块共享

javascript - 区间函数