代码之家  ›  专栏  ›  技术社区  ›  mr__brainwash

在typescript中,是否有任何方法可以将对象用作键?

  •  0
  • mr__brainwash  · 技术社区  · 6 年前

    我有两个班:

    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 接口,因为在typescript中

    索引签名参数类型必须是“string”或“number”

    1 回复  |  直到 6 年前
        1
  •  2
  •   str    6 年前

    在typescript中,是否有任何方法可以将对象用作键?

    不,不带对象文本。

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

    这个 Map 对象保留键值对。 任何值(对象和基元值)都可以用作键或值。