typescript - 界面自动识别类型
问题描述
我有一个类似这样的界面:
interface ValueGetter<T> {
property: keyof T;
getValueFunction: (value: any) => value;
}
我希望能够提供自定义getValueFunction
来访问 的某些属性T
,但在定义正确的类型和替换any
.
鉴于我需要的以下界面是:
interface Person {
name: string;
age: number;
}
const valueGetter: ValueGetter<Person> = {
property: 'name',
getValueFunction: …
// I want here the type checker to recognize that the
// correct type of this function should be: (value: string) => string, because
// the property 'property' is 'name' and the type of Person['name'] is string.
}
如果我想访问其他属性age
:
const valueGetter: ValueGetter<Person> = {
property: 'age',
getValueFunction: … Expected type: (value: number) => number
}
解决方案
您可以通过将所需的属性键作为类型参数添加到ValueGetter
接口来解决此问题。
所以像:
interface ValueGetter<T, K extends keyof T> {
property: K;
getValueFunction: (value: T[K]) => T[K];
}
const valueGetter: ValueGetter<Person, 'age'> = {
property: 'age', // here you can only enter 'age' now, nothing else
getValueFunction: … Expected type: (value: number) => number
}
推荐阅读
- laravel - How can I assert an instance of a ResourceCollection in Laravel?
- rest - 如何从 Salesforce 界面启动 UiPath 流程
- mysql - inner join and count records recursively
- javascript - Countdown timer in JavaScript not stopping
- javascript - .XLS 文件格式对 react-export-excel 第三方库无效
- linux - 是否存在适用于 Linux 的展讯 USB 驱动程序?
- json - How can I minify JSON in a shell script?
- python - Tank collides with walls in pygame
- python - Translating a CURL call to Python script
- cordova - iOS 应用内购买 - 如何针对生产服务器进行调试?