Get the App
SLTechnology News&Howtos  ›  Development  › 

How to solve the problem of traversing object properties in TypeScript

Shulou Source: shulou.com Published: 2022-06-02 16:18:46 09月18日 Update

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!

Tags: Objects problems attributes learning content methods codes methods that is tools common ideas situations interfaces articles more mechanisms knowledge knowledge points articles Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Tech Info Microsoft Shulou Information Redmi Linux