使用打字稿中的变量访问对象键 [英] Access object key using variable in typescript
问题描述
在打字稿中,如何使用变量访问对象键(属性)?
In typescript, How to access object key(property) using variable?
例如:
interface Obj {
a: Function;
b: string;
}
let obj: Obj = {
a: function() { return 'aaa'; },
b: 'bbbb'
}
for(let key in obj) {
console.log(obj[key]);
}
但打字稿会抛出以下错误消息:
but typescript throw below error message:
'TS7017 元素隐式具有 'any' 类型,因为类型 'obj' 没有索引签名'
'TS7017 Element implicitly has an 'any' type because type 'obj' has no index signature'
如何解决?
推荐答案
要使用 --noImplicitAny
编译此代码,您需要具有某种类型检查版本的 Object.keys(obj)
函数,在某种意义上进行了类型检查,已知它仅返回 obj
中定义的属性名称.
To compile this code with --noImplicitAny
, you need to have some kind of type-checked version of Object.keys(obj)
function, type-checked in a sense that it's known to return only the names of properties defined in obj
.
TypeScript AFAIK 中没有内置这样的函数,但您可以提供自己的:
There is no such function built-in in TypeScript AFAIK, but you can provide your own:
interface Obj {
a: Function;
b: string;
}
let obj: Obj = {
a: function() { return 'aaa'; },
b: 'bbbb'
};
function typedKeys<T>(o: T): (keyof T)[] {
// type cast should be safe because that's what really Object.keys() does
return Object.keys(o) as (keyof T)[];
}
// type-checked dynamic property access
typedKeys(obj).forEach(k => console.log(obj[k]));
// verify that it's indeed typechecked
typedKeys(obj).forEach(k => {
let a: string = obj[k]; // error TS2322: Type 'string | Function'
// is not assignable to type 'string'.
// Type 'Function' is not assignable to type 'string'.
});
这篇关于使用打字稿中的变量访问对象键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!