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 Suzanne D. Williams en Unsplash
Top comments (5)
Nice, 🙂 if something doesn't feel right, there is always a solution in typescript. I think all typescript developers should use these utilities link
I just wrote a post about a typescript solution, what do you think? blog post
I was surprised that many TypeScript developers do not even know about the utilities
Typescript gives you too many options, which are often good. But also you don't need to learn the correct way you can do "as any" and the problem is "solved". My typescript pilosophi is eliminate all "any" types and create types what can't be used wrongly 😄
I personally care very much about the purity and fidelity of my code, just in my sad experience, as you said: do whatever you want, the main thing to solve the problem, but this unfortunately leads the whole project to a bunch of bugs or an incomprehensible code base
Thanks for your feedback!! Amazing contribution, very helpful!!!! (I will update the article with your feedback)