Hi Folks! It's nice to have you again!
In this small article I will talk about the Utility Types of Typescript
Utility types are features available on all typescript code. So let's see some them:
Utility Types For Objects
First let's define some object as type:
type User = {
id: number;
name: string;
userName?: string;
}
Partial
Makes the all the properties of the type undefined.
type PartialUser = Partial<User>;
Required
Makes all the properties of the type required.
type RequiredUser = Required<User>;
Omit
We can omit some property of the type and create a new type without it.
type OmitUserUsername = Omit<User, "userName">;
We can pass an union types for more properties:
type OnlyId = Omit<User, "userName" | "name">;
Pick
Unlike Omit, we can pick some property of the type
type PickId = Pick<User, "id">;
And as Omit, We can pass an union types for more properties:
type WithoutUser = Pick<User, "id" | "userName">;
ReadOnly
Turns the properties read-only
type ReadOnlyUser = Readonly<User>;
If we try to change some property we will have some error:
Utility Types For Union Types
Let's create our Union Type:
type Role = "admin" | "user" | "manager";
Exclude
It will remove some type of the union types
type NoUserRole = Exclude<Role, "user">;
Extract
Let's create another union types:
type RoleAttributes =
| {
role: "admin";
permission: "all";
}
| {
role: "user";
}
| {
role: "manager";
};
Now let's extract the admin
using:
type AdminRole = Extract<RoleAttributes, { role: "admin" }>;
NonNullable
Let's define a union type where the result can be a string, null or undefined;
type MaybeString = string | null | undefined;
type NonNullableString = NonNullable<MaybeString>;
Utility Types For Functions
Let's define our type of function:
type myFunction = (a: number, b: number) => number;
ReturnType
It will return the type of the return
of the function
type ReturnValueFunction = ReturnType<myFunction>;
Parameters
It will return a tuple of the parameters of the function:
type MyParameters = Parameters<myFunction>;
Awaited
It will return the type of a Promise
Let's define a type of Promise
type PromiseUser= Promise<User>;
type Result = Awaited<PromiseUser>;
And that's it guys! Let's see some challenge?
Define the type of the result of this async function:
const getMyName = async () => {
return {
name: "Kevin",
};
};
How we can get a object type that is a string?
The answer:
type MyNameResult = Awaited<ReturnType<typeof getMyName>>;
So, thank you guys for getting this far.
That's it, the Typescript offers some utility types that can help you on your development.
Contacts:
Linkedin: https://www.linkedin.com/in/kevin-uehara/
Instagram: https://www.instagram.com/uehara_kevin/
Twitter: https://twitter.com/ueharaDev
Github: https://github.com/kevinuehara
Youtube Channel: https://www.youtube.com/channel/UC6VSwt_f9yCdvEd944aQj1Q
Top comments (1)
Take your TypeScript skills to new heights with "Mastering TypeScript Core Utility Types":
๐ Buy on Leanpub
๐ Buy on Amazon