首页 > 解决方案 > 界面自动识别类型

问题描述

我有一个类似这样的界面:

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
}

标签: typescript

解决方案


您可以通过将所需的属性键作为类型参数添加到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
}

推荐阅读