简体   繁体   English

如何在 typescript 中使用类型化 object 的 function 获取属性

[英]How to get property using function of a typed object in typescript

Here is the interface:这是界面:

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

Now I want to use the getProperty function to get the value based on key of object.现在我想使用 getProperty function 根据 object 的键获取值。

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

    return obj[key];
}

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

Now it returns the error现在它返回错误

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

How should i solve this?我应该如何解决这个问题?

Remove the key:string part删除key:string部分

 let key:any = 'State'

getProperty function defined 2nd parameter key as keyof Context , so you need to define variable key in a similar way: getProperty function 将第二个参数key定义为keyof Context ,因此您需要以类似的方式定义变量key

let key: keyof IContext = 'State';

Assuming that IContext is the name of your interface.假设IContext是您的接口的名称。 Full example would look like this:完整示例如下所示:

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM