遍历对象属性
在TypeScript里面,当需要遍历对象的时候,经常就会遇到下图所示的错误提示。
function test (foo: object) {
for (let key in foo) {
console.log(foo[key]); // typescript错误提示
// do something
}
}
有两个报错
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'.
因为foo作为object没有声明string类型可用,所以foo[key]将会是any类型。
No index signature with a parameter of type 'string' was found on type '{}'.
object没有找到string类型的
解决方法
那么,针对这种情况,我们有几种解决方法
- 把对象声明as any
function test (foo: object) {
for (let key in foo) {
console.log((foo as any)[key]); // 报错消失
// do something
}
}
复制代码但是这个方法有点像是直接绕过了typescript的校验机制,失去了使用typescript的初心,这不是我们想要的。
- 给对象声明一个接口
interface SimpleKeyValueObject {
[key: string]: any
}
function test (foo: SimpleKeyValueObject) {
for (let key in foo) {
console.log(foo[key]); // 报错消失
// do something
}
}
这个可以针对比较常见的对象类型,特别是一些工具方法。
但是这个不够骚,能不能再厉害点呢~
- 使用泛型
function test<T extends object> (foo: T) {
for (let key in foo) {
console.log(foo[key]); // 报错消失
// do something
}
}
当我们需要对foo的key进行约束时,我们可以使用下面的第4种方法。
- 使用keyof
interface Ifoo{
name: string;
age: number;
weight: number;
}
function test (opt: Ifoo) {
let key: (keyof Ifoo);
for (key in opt) {
console.log(opt[key]); // 报错消失
// do something
}
}
作者:Rio_Kwok
链接:https://juejin.cn/post/6844904147146260488
来源:稀土掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
网友评论