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]
Built on Forem — the open source software that powers DEV and other inclusive communities.
Made with love and Ruby on Rails. DEV Community © 2016 - 2024.