mr__brainwash
mr__brainwash

Reputation: 1382

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

I have tow classes:

class A {
  name: string;
  age: number;

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

class B extends A {

}

Also i have an object where i want to use instances of these classes as keys:

const storage: Storage = {};

So it will look like this:

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.'

And then i want to differ value by keys, like:

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');
  }
})

How should looks like Storage interface, because in typescript

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

Upvotes: 0

Views: 171

Answers (1)

str
str

Reputation: 45019

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

No, not with object literals.

However, you can use a Map instead:

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

Upvotes: 2

Related Questions