Khizar Ali
Khizar Ali

Reputation: 514

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.

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?

Upvotes: 1

Views: 1854

Answers (2)

abhijat_saxena
abhijat_saxena

Reputation: 970

Remove the key:string part

 let key:any = 'State'

Upvotes: 1

Nenad
Nenad

Reputation: 26687

getProperty function defined 2nd parameter key as keyof Context, so you need to define variable key in a similar way:

let key: keyof IContext = 'State';

Assuming that IContext is the name of your interface. 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);

Upvotes: 0

Related Questions