如何在打字稿中的对象中 select 属性
How to select property in object in typescript
如何根据作为第二个参数传递给函数的内容来 select 对象 属性?
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")
可以这样写:args[key]
更好的方法是将第二个参数限制为对象本身可用的可用键的参数,例如:
function foo(args: Type, key: keyof Type) {
console.log(args[key]);
}
然后调用方法:
foo({ first: "hi", second: "man" }, "first")
以下导致错误:
foo({ first: "hi", second: "man" }, "somethingElse")
如何根据作为第二个参数传递给函数的内容来 select 对象 属性?
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")
可以这样写:args[key]
更好的方法是将第二个参数限制为对象本身可用的可用键的参数,例如:
function foo(args: Type, key: keyof Type) {
console.log(args[key]);
}
然后调用方法:
foo({ first: "hi", second: "man" }, "first")
以下导致错误:
foo({ first: "hi", second: "man" }, "somethingElse")