javascript - 使用打字稿中的通用类型从具有正确类型的对象返回属性
问题描述
我曾多次尝试实现从对象中提取属性的通用函数。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
解决方案
使偏函数泛型,它将能够根据特定的字符串值推断返回值的类型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');
推荐阅读
- javascript - 如何在highcharts中动态显示地图图表反应
- sql - 如何在大查询中查找具有特定列名的所有表和数据集/数据库
- python - 等到桌面应用程序打开并从 python 中的 rpaframework 库加载
- android - 基于点击事件android录制和保存音频
- spring - DelegatingProxyFilter 与 OncePerRequestFilter
- database - 更好的是,将所有数据存储在数据库中还是每次从 API 中获取?
- browser-automation - 419 | 页面仅在 Pytest 自动化中过期,不在手动中
- r - 为维恩图的交点着色
- file - 检测给定文件是 gzip 还是 TarGzip
- html - 为什么我的 html 代码元素标签中的内容不自动换行?