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 traverse an object correctly in TypeScript

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly introduces how to correctly traverse an object in the TypeScript related knowledge, the content is detailed and easy to understand, the operation is simple and fast, has a certain reference value, I believe that everyone after reading this article on how to correctly traverse an object in TypeScript will have a harvest, let's take a look at it.

JavaScript

Before we talk about traversing an object with Ts, let's talk about how to do it in Js. For...in, Object.keys, a simple example:

/ / for...inconst obj = {name: 'itsuki', address:' hangzhou',}; for (const key in obj) {console.log (key, obj [key]. ToUpperCase ());} / / Object.keysObject.keys (obj) .forEach (key = > {console.log (key, objkey]. ToUpperCase ();}); / / output / / name ITSUKI// address HANGZHOUTypeScriptfor...in

But in TypeScript, if you use it this way directly, you will report an error.

Type Person = {name:string; address: string;}; const obj: Person = {name: 'itsuki', address:' hangzhou',}; function print (obj: Person) {for (const key in obj) {/ / ❌ / / key:string cannot be assigned to {name:string; age:number} type console.log (key, obj [key]. ToUpperCase ());} print (obj)

We know that for...in and Object.keys get the object's key, and all key in the object are strings, so it cannot be assigned to Person's name, address.

But we can solve this problem by keyof.

Function print (obj:Person) {let key: keyof Person; for (key in obj) {/ / ✅ console.log (key, obj [key]. ToUpperCase ());} Object.keys

When using Object.keys, we can use as operator to solve the problem.

Function print (obj: Person) {Object.keys (obj) .forEach ((k) = > {/ / ✅ console.log (k, obj [k as keyof Person]. ToUpperCase ());});}

We can extract this from a function:

Function getKeys (obj: t) {return Object.keys (obj) as Array;} getKeys (obj); / / (keyof Person) [] Object.entries

We can also use Object.entries () to traverse the object.

Object.entries (obj) .forEach (([k, v]) = > {console.log (k, v);})

The following is my own thinking. If there are any mistakes, please correct them.

I think Object.keys () returns a string [] because it is determined at run time, and we know that TypeScript is only doing static type checking, even if we return name | address using keyof Person, we are not sure that it is these two fields at run time.

For example:

Const obj2 = {name: 'itsuki', address:' hangzhou', age: 20,}; print (obj2) / / compile time: ✅, because it has name, address attributes / / runtime: ❌, because the age field is number and there is no toUpperCase method

And then I found this sentence in Github issue:

Types in TS are open. As a result, the keysof may be less than all the properties obtained at run time.

It makes me understand why keys () returns a string [] instead of a (keyof Person) [].

This is the end of the article on "how to traverse an object correctly in TypeScript". Thank you for reading! I believe that everyone has a certain understanding of "how to correctly traverse an object in TypeScript". If you want to learn more knowledge, you are welcome to follow the industry information channel.

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