Photo by Suzanne D. Williams on Unsplash
3 Ways of Type Transformation in Typescript
Use the power of compiler and Typescript together
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.
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