typescript - 如何声明 Typescript 函数返回命名属性的类型?
问题描述
我想输入接口属性的名称,并返回具有该属性类型的内容。那可能吗?例如:
interface FooInterface {
x: number;
y: string;
}
function fooFunction(data: FooInterface, name: keyof FooInterface) {
return data[name];
}
let fooVar = fooFunction({ x: 123, y: "hello" }, "x"); // <- Is it possible to make this smart enough to understand that fooVar is now a number?
解决方案
是的,您只想创建fooFunction()
一个具有类型参数的泛型函数,该类型参数K
被限制为keyof FooInterface
. 参数将name
是这种泛型类型K
:
function fooFunction<K extends keyof FooInterface>(data: FooInterface, name: K) {
return data[name];
}
现在编译器推断data[name]
返回通用索引访问类型 FooInterface[K]
而不是string | number
.
当您调用fooFunction()
时,编译器将根据您传入K
的参数进行推断:name
let fooVar = fooFunction({ x: 123, y: "hello" }, "x");
// function fooFunction<"x">(data: FooInterface, name: "x"): number
既然K
是用 指定的"x"
,那么函数返回FooInterface["x"]
的就是number
。所以fooVar
众所周知的是number
:
// let fooVar: number
fooVar.toFixed(2); // okay no compiler error
推荐阅读
- c# - Linq - 过滤内部列表
- kubernetes - 即使我的服务仅使用 HTTPS,GKE 入口也会在 HTTP 中回答
- sublimetext3 - 使用 Sublime Text 3 运行 Scriptcs 时出错
- angular - 如何使每个离子滑梯根据它所拥有的数据采用它的高度?
- react-native - 反应本机状态不更新
- angular - 导入和导出只能出现在顶层
- java - *First* 最长递增子序列
- android - 对 com.google.firebase.functions.ContextProvider 的依赖不满足
- php - 获取十六进制背景颜色的逆值 - PHP
- iot - 如何更改 Node-RED 仪表板的路径