Dany Paredes
Dany Paredes | Javascript / Web

Dany Paredes | Javascript / Web

3 Ways of Type Transformation in Typescript

Photo by Suzanne D. Williams on Unsplash

3 Ways of Type Transformation in Typescript

Use the power of compiler and Typescript together

Dany Paredes's photo
Dany Paredes
·Jul 19, 2022·

2 min read

Subscribe to my newsletter and never miss my upcoming articles

Play this article

When we use types or interfaces, the typescript compiler enforces the object fit with them to avoid runtime errors for missing fields.

Sometimes we want the flexibility to create an object without breaking the contract with the interface type.

For example, we have the interface User with all properties required.

interface User {
  username: string;
  password: string;
  roles: string[];
  active: boolean;
}

Maybe we want to create a user and later call the API to get the roles. If we try to make the object without all the properties, the compiler shows an error because it doesn't fit with the interface.

Error compilers missing properties

In most cases, we change the property to optional roles?: string[] and to allow compiling, but we know it is a cheat.

Typescript provides the utility to work with it:

Partial: Create a new type with all properties as optional from the type:

let admin: Partial<User> = {
  username: 'admin',
  password: 'admin'
}

Thanks to @lukeshiru contribution, I learn other ways to deal with it:

Partial makes every property optional. Maybe it is not what we want.

Typescript provides other Utility types, Omit and Pick let play with it.

Omit: Create a new type taking all properties from the type and removing the keys.

type UserWithoutRoles = Omit<User, "roles">;

const userWithoutRoles: UserWithoutRoles = {
    username: "admin",
    password: "admin",
};

Pick: Create a new type from the type and pick a set of properties.

type UserWithStatus = Pick<User, "username" | "active">

const userWithStatus: UserWithStatus = {
    username: "dany",
    active: true
}

Thanks again to @lukeshiru :)

Learn more about Typescript Utility Types

Read more articles in www.danywalls.com Foto de Suzi Kim en Unsplash

Did you find this article valuable?

Support Dany Paredes by becoming a sponsor. Any amount is appreciated!

Learn more about Hashnode Sponsors
 
Share this