首页 > 解决方案 > 如何声明 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?

标签: typescript

解决方案


是的,您只想创建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

Playground 代码链接


推荐阅读