TypeScript遍历对象属性的问题
这篇文章主要介绍了TypeScript遍历对象属性的问题,文章围绕TypeScript遍历对象属性的相关资料展开详细内容,需要的朋友可以参考一下
目录
一、问题
二、解决办法
1. 把对象声明as any
2. 给对象声明一个接口
3. 使用泛型
4. 使用keyof
一、问题
比如下面的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | type Animal = { name: string; age: number } const animal:Animal={ name: "dog" , age:12 } function test(obj:Animal) { for (let k in obj) { console.log(obj[k])。 //这里出错 } } test(animal) |
报错:
二、解决办法
1. 把对象声明as any
1 2 3 4 5 | function test(obj:Animal) { for (let k in obj) { console.log((obj as any)[k]) //不报错 } } |
这个方法直接绕过了typescript
的校验机制
2. 给对象声明一个接口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | type Animal = { name: string; age: number; [key: string]: any } const animal:Animal={ name: "dog" , age:12 } function test(obj:Animal) { for (let k in obj) { console.log(obj [k]) //不报错 } } test(animal) |
这个可以针对比较常见的对象类型,特别是一些工具方法。
3. 使用泛型
1 2 3 4 5 | function test<T extends object>(obj:T) { for (let k in obj) { console.log(obj [k]) //不报错 } } |
4. 使用keyof
1 2 3 4 5 6 | function test(obj:Animal) { let k: (keyof Animal); for (k in obj) { console.log(obj [k]) //不报错 } } |
到此这篇关于TypeScript遍历对象属性的问题的文章就介绍到这了
原文链接:https://www.cnblogs.com/gg-qq/p/15508536.html