如何在打字稿中选择对象中的属性

时间:2021-01-19 08:38:11

标签: typescript interface

如何根据作为第二个参数传递给函数的内容来选择对象属性?

interface Type{
  first:string;
  second:string;
}

function foo(args:Type,key:string) {
  console.log(args.key)//if key=="first" select args.first, if key=="second" select args.second
}

foo({first:"hi",second:"man"},"first")

2 个答案:

答案 0 :(得分:-1)

你可以这样写:args[key]

答案 1 :(得分:-1)

这样做的更好方法是将第二个参数限制为对象本身可用的可用键的参数,例如:

AsyncStorage

然后调用方法:

function foo(args: Type, key: keyof Type) {
    console.log(args[key]);
}

以下导致错误:

foo({ first: "hi", second: "man" }, "first")