DEV Community

Dennis Cual
Dennis Cual

Posted on • Edited on

Typescript hack: Simple utility type for changing type of keys

When making all keys optional in Typescript, we gonna use the utility type Partial. But what if we want to change the type of some keys of
given object type?

I created a simple utility type to achieve this goal. First of all, I will show you how to use it and lastly show the codes.

type User = {
  id: number
  name: string
  age: number
  hobbies: []
}

type OtherUser = ChangeTypeOfKeys<User, 'id' | 'age', string>

This is simple utility. First, it accepts the target object type. Then the keys, its a union type, we want to change and lastly pass the new type. The created type of OtherUser will have a shape like this:

type OtherUser = {
 id: string
 name: string
 age: string
 hobbies: []
}

Sweet! We just changed the type of keys from number to string. The codes for this utility type:

/**
 * Change the type of Keys of T from NewType
 */
export type ChangeTypeOfKeys<
  T extends object,
  Keys extends keyof T,
  NewType
> = {
  // Loop to every key. We gonna check if the key
  // is assignable to Keys. If yes, change the type.
  // Else, retain the type.
  [key in keyof T]: key extends Keys ? NewType : T[key]
}

Thats all! If you think this is helpful. Like and share!

Top comments (1)

Collapse
 
shanike profile image
Shani Kehati

Hi,
That seems very interesting, can you provide an example for the ChangeTypeOfKeys type?