如何在打字稿中使用键入对象的功能获取属性

时间:2020-04-28 08:33:26

标签: javascript object typescript-typings

这是界面:

interface {
    State?: string;
    Profession?: string;
}

现在我想使用getProperty函数基于对象的键获取值。

function getProperty<Context, K extends keyof Context>(obj: Context, key: K): Context[K] {

    return obj[key];
}

let key: string = 'State';
getProperty(context, key);

现在它返回错误

> TSError: ⨯ Unable to compile TypeScript: index.ts:50:33 - error
> TS2345: Argument of type 'string' is not assignable to parameter of
> type '"State" | "Profession"'.

我应该如何解决?

2 个答案:

答案 0 :(得分:1)

删除key:string部分

 let key:any = 'State'

答案 1 :(得分:0)

getProperty函数将第二个参数key定义为keyof Context,因此您需要以类似的方式定义变量key

let key: keyof IContext = 'State';

假设IContext是您的界面的名称。完整的示例如下所示:

interface IContext {
    State?: string;
    Profession?: string;
}

function getProperty<Context, K extends keyof Context>(obj: Context, key: K): Context[K] {

    return obj[key];
}

let key: keyof IContext = 'State'; // should not be a string
const context: IContext = {}; // instance of IContext

getProperty(context, key);