Home > Mobile >  How get value from object if i have variable with key of this object in typescript
How get value from object if i have variable with key of this object in typescript

Time:10-02

type person ={
  name: string,
  age: number,
  gender: ('male'|'female'),
}
let man: person= {
  name: 'bob',
  age: 10,
  gender: 'male',
}
let k1:string[] = Object.keys(man)
let s: string = k1[1]
console.log(man[s])// why mistake??????
console.log(typeof s)//string

Why i can not write 'man[s]' to get value and what i should do to get it? VS code wrote this error ' The element is implicitly of type "any" because an expression of type "string" cannot be registered in the Republic for indexing type "person". No index signature was found on type 'person' with type parameter 'string'.'

CodePudding user response:

Because k1 is a string array. That means that s can be a string. Any string. And TS doesn't like it when you try to index an array with any random string.

Now we know that s will always be a key of man. So we can tell typescript that.

type person ={
  name: string,
  age: number,
  gender: ('male'|'female'),
}
let man: person= {
  name: 'bob',
  age: 10,
  gender: 'male',
}
let k1 = Object.keys(man) as (keyof person)[]
let s = k1[1]
console.log(man[s])
console.log(typeof s)

That being said, you should probably not rely on the order of the keys from Object.keys. It is implementation specific from the spec.

If an implementation defines a specific order of enumeration for the for-in statement, the same order must be used for the elements of the array returned in step 4.

And for enumerables:

The mechanics and order of enumerating the properties is not specified but must conform to the rules specified below.

  • Related