TransWikia.com

TypeScript: Why having a `keyof` here can solve this issue

Stack Overflow Asked on January 9, 2021

I was trying to write a function to return an array of values in an object

  a: 1,
  b: 2,
  c: 3,
}

const r = Object.keys(obj).map((key) => {
  let val = obj[key]
  return val
})

Here the TS compiler showed an error saying that

Element implicitly has an ‘any’ type because expression of type
‘string’ can’t be used to index type ‘{ a: number; b: number; c:
number; }’. No index signature with a parameter of type ‘string’ was
found on type ‘{ a: number; b: number; c: number; }’.ts(7053)

I cannot decipher what it means but I thought it has something to do with key being a string. so I tried this instead

let obj = {
  a: 1,
  b: 2,
  c: 3,
}

const r = Object.keys(obj).map((key) => {
  let val = obj[key as keyof typeof obj] // the error now is gone
  return val
})

console.log('r', r)

Now there is no error. I am not exactly sure why. all I know is that keyof would yields the type of permitted property names on the obj but I don’t know what purpose typeof serves here

One Answer

Typescript infers the typing of your obj object to be:

type Obj = {
  a: number
  b: number
  c: number
}

This can also be expressed as:

type Obj = {[key in 'a' | 'b' | 'c']: number};

'a' | 'b' | 'c' is a subtype of string. When you use Object.keys(obj) however, typescript infers the return type here to be string[] as opposed to ('a' | 'b' | 'c')[]. This is why it complains about No index signature with a parameter of type 'string' was found on type '{ a: number; b: number; c: number; }' - because you cannot use any string to look up values in obj, rather you need to use specific keys.

The keyof operator takes a type as an input, and returns the keys provided. The reason you need typeof is to infer the type of an object (otherwise you'd be doing keyof obj, which typescript does not understand as obj is not a type)

keyof typeof obj is inferred as "a" | "b" | "c"

Keyof - https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-1.html#keyof-and-lookup-types

Typeof - https://mariusschulz.com/blog/type-queries-and-typeof-in-typescript#typescripts-type-queries

Answered by g2jose on January 9, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP