1. ProblemFor 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: 2. Solution 1. Declare the object as anyfunction test(obj:Animal) { for (let k in obj) { console.log((obj as any)[k]) //No error} } This method directly bypasses the 2. Declare an interface for the objecttype 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} } test(animal) This can be used for more common object types, especially some tool methods. 3. Use Genericsfunction test<T extends object>(obj:T) { for (let k in obj) { console.log(obj [k]) //No error} } 4. Use keyoffunction test(obj:Animal) { let k: (keyofAnimal); for (k in obj) { console.log(obj [k]) //No error} } This is the end of this article about TypeScript traversing object properties. For more information about TypeScript traversing object properties, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future! You may also be interested in:
|
<<: Table setting background image cannot be 100% displayed solution
>>: CSS realizes the scene analysis of semi-transparent border and multiple border
Table of contents 1. Usage of DATETIME and TIMEST...
And, many times, maintenance requires your website...
Carousel animation can improve the appearance and...
Today, when we were learning about the Niu Nan new...
Application example website http://www.uhuigou.net...
This reading note mainly records the operations r...
1. Scenario description: My colleague taught me h...
HTML stands for Hypertext Markup Language. Nowada...
Preface: The Linux host is relatively easy to han...
Table of contents 1. Download MySQL 2. Install My...
Innodb includes the following components 1. innod...
Table of contents 1. Introduction 2. Several ways...
As shown below, if it were you, how would you ach...
1. Advantages and Disadvantages of Indexes Advant...
Table of contents 1. What is Dockerfile? 2. Analy...