Home > Enterprise >  How can I get the type of a keyof variable in Typescript?
How can I get the type of a keyof variable in Typescript?

Time:03-20

I have the following interface:

interface MyInterface { 
   a: string 
   b: number 
}

and the following Function:


function myFunction(key: keyof MyInterface, someItem: MyInterface) {
  if (key === "a") {
    throw new Error("Key is not corresponding to a number")
  }
  
  return someItem[key]
}

It's working, but I have a much bigger interface and I'd like to avoid hardcoding all the keys, that don't correspond to a number. Is there an easy way to do this?

CodePudding user response:

We can get all the number keys with a type like this:

type NumberKeys<T> = {
    [K in keyof T]: T[K] extends number ? K : never;
}[keyof T];

Mapping over each key, we test if each key's value is a number. If it is, we map it to itself, otherwise, it's never.

Then finally, we get all of the results as a union with [keyof T]. Because T | never is always T, we only get the keys that are numbers left.

Playground

  • Related