[英]How to select property in object in typescript
How can I select object property depending on what is passed to the function as a second argument?我如何 select object 属性取决于作为第二个参数传递给 function 的属性?
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")
You can write it like this: args[key]
你可以这样写:
args[key]
A better way of doing this is to restrict the second argument to that of the available keys that are available on the object itself, such as:更好的方法是将第二个参数限制为 object 本身可用的可用密钥,例如:
function foo(args: Type, key: keyof Type) {
console.log(args[key]);
}
Then call the method:然后调用方法:
foo({ first: "hi", second: "man" }, "first")
The following results in an error:以下导致错误:
foo({ first: "hi", second: "man" }, "somethingElse")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.