DEV Community

Dennis Cual
Dennis Cual

Posted on • Edited on

9 1

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!

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (1)

Collapse
 
shanike profile image
Shani Kehati

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

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay