Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to solve the problem of traversing object properties in TypeScript

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "how to solve the problem of TypeScript traversing object attributes". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to solve the problem of TypeScript traversing object attributes".

First, problems

For example, the following code:

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]). / / error here}} test (animal)

Error report:

Second, the solution 1. Declare an object to as any

Function test (obj:Animal) {for (let k in obj) {console.log ((obj as any) [k]) / / No error}}

This method directly bypasses the verification mechanism of typescript.

two。 Declare an interface to the object 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]) / / No error reporting} test (animal)

This can be targeted at the more common object types, especially some tool methods.

3. Use generic function test (obj:T) {for (let k in obj) {console.log (obj [k]) / / No error} 4. Use keyoffunction test (obj:Animal) {let k: (keyof Animal) For (k in obj) {console.log (obj [k]) / / No error}} Thank you for your reading, this is the content of "how to solve the problem of TypeScript traversing object attributes". After the study of this article, I believe you have a deeper understanding of how to solve the problem of TypeScript traversing object attributes, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report