这是界面:
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"'.
我应该如何解决?
答案 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);