我有两门课:
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/