首页 > 解决方案 > 使用打字稿中的通用类型从具有正确类型的对象返回属性

问题描述

我曾多次尝试实现从对象中提取属性的通用函数。Typescript 下面的代码返回字符串 | 数字,虽然我想让它知道它会专门返回一个字符串或一个数字。在普通的 JS 中,我会知道下面的代码会返回一个字符串并做出相应的反应,所以我希望可以阐明如何在 Typescript 中解决这个问题。

interface Person {
  name: string;
  age: number;
}

const getPropertyByKey = (
  person: Person
) => (
  key: keyof Person
) => person[key];

const person = {
  name: 'Thomas',
  age: 32
};

const property = (person)('name'); // Should realise it is a string

标签: javascripttypescriptgeneric-programming

解决方案


使偏函数泛型,它将能够根据特定的字符串值推断返回值的类型key

interface Person {
  name: string;
  age: number;
}

const getPropertyByKey = (
  person: Person
) => <K extends keyof Person>(
  key: K
) => person[key];

const person = {
  name: 'Thomas',
  age: 32
};

const property = getPropertyByKey(person)('name');

游乐场链接


推荐阅读