[英]How to define a function's argument type as one of the keys (or properties) of an interface
假设你有这个界面:
interface IExample {
a: string;
b: {
b1: string;
b2: string | number | boolean;
};
}
你有一个 function 像:
const foo = (arg) => {
//function's logic
}
现在我想从IExample
将arg
输入为b
,例如:
const foo = (arg: IExample.b): void => { // this generates an error
//function's logic
}
需要明确的是,函数的参数应该是:
{
b1: string;
b2: string | number | boolean;
}
而且我不想为此编写另一个界面。
我自己找不到方法,也没有通过阅读 typescript 文档来弄清楚。 这是我最后的希望。
您使用[]
来索引类型。 一些关于此的文档是here。
function foo(arg: IExample['b']): void {
//function's logic
}
foo({ b1: 'abc', b2: true })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.