Reputation: 514
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
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