如何使用get方法访问Typescript中对象的字段?

How to access a field of an object in Typescript using get method?

在 Typescript 中我定义了一个接口:

interface IPriority {
    KEY1: number;
    KEY2: number;
    KEY3: number;
    DEFAULT: number;
}

我将类型为 IPriority 的对象传递给函数,如下所示:

    class Foo {
        async someFunction(priority: IPriority) {
        const someMap: Map<string, string> = new Map();
        //someMap has been properly initialized and has valid data
        const key = someMap.get("KEY1") ?? "KEY1";
        //const key = "KEY1";
        if(key) {
          const temp = priority[key];
          console.log(temp);
        }
      }
    }

这样做,我得到这个错误:Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'IPriority'. No index signature with a parameter of type 'string' was found on type 'IPriority'.

如果我将 const temp = priority[key]; 更改为 const temp = priority.get(key),我会收到此错误:Property 'get' does not exist on type 'IPriority'.

如何使用 get 方法或对象索引语法 (priority[key]) 访问 KEY1KEY2、...的值?

这是 link 到 code

显然编译器需要索引的预定义值。您有两个选择:

  1. 像这样使用 any 关键字 (priority as any)[key]
  2. 创建字典见

正如 Alireza Ahmadi 所说,最好在打字稿中使用字典而不是 interfaceMap。但是如果你想坚持你的代码并使用编写的代码,你可以找到 founded key 的值,其中有两个定义在 Object 上的函数:Object.keysObject.values .您可以将 someFunctions 方法更改为如下内容:

interface IPriority {
  KEY1: string;
  KEY2: string;
  KEY3: string;
} 

class Foo {
   async someFunction(priority: IPriority) {
      const someMap: Map<string, string> = new Map();
      someMap.set("1", "KEY1");
      someMap.set("2", "KEY2");
      someMap.set("3", "KEY3");
      const key1 = someMap.get("1");
      if (key1) {
         let value: string = "";
         Object.keys(priority).map((propertyKey, propertyIndexKey) => {
           if (propertyKey == key1) {
              Object.values(priority).map((propertyValue, propertyIndexValue) => {
                 if (propertyIndexKey == propertyIndexValue) {
                    value = propertyValue;
                 }
           })
        }
        return value;
        })
        console.log(value);
     }
  }
}

const foo: Foo = new Foo();
const priority: IPriority = {
  KEY1: "1",
  KEY2: "2",
  KEY3: "3",
}
foo.someFunction(priority)// "1"