Implementing Your Own Utility Types in TypeScript
Creating your own utility types allows you to write custom types tailored to your needs, independent of the built-in TypeScript utilities. This is important both for learning and for crafting specialized type solutions in projects.
Sample Type: MyUtilTypes
type MyUtilTypes = {
method: 'post' | 'get';
url: string;
body: object;
}
First, we define a simple type to work with: it has method, url, and body fields commonly used in HTTP requests.
MyPick: Selecting Specific Keys from a Type
// My Pick: Select specific keys from a type
type MyPick<T extends object, K extends keyof T> = {
[P in K]: T[P];
};
type testMyPick = MyPick<MyUtilTypes, 'method' | 'body'>;
// Result: { method: 'post' | 'get'; body: object }
`MyPick` creates a new type by picking only the specified keys from a given type. This way, we can extract just the properties we need.
MyExclude: Excluding Keys from a Union Type
// My Exclude: Exclude keys from a union type
type MyExclude<T, K extends T> = T extends K ? never : T;
type testMyExclude = MyExclude<keyof MyUtilTypes, 'method'>;
// Result: "url" | "body"
`MyExclude` removes specified keys from a union type. It is commonly used as a helper in other utility types.
MyPartial: Making All Properties Optional
// My Partial: Make all properties optional (without -? it would keep required)
type MyPartial<T extends object> = {
[P in keyof T]?: T[P];
};
type testMyPartial = MyPartial<MyUtilTypes>;
// Result: { method?: 'post' | 'get'; url?: string; body?: object }
`MyPartial` makes all properties optional. This is useful for partial updates or when fields are not mandatory.
MyOmit: Removing Specific Keys from a Type
// My Omit: Remove specific keys from type
type MyOmit<T extends object, K extends keyof T> = {
[P in MyExclude<keyof T, K>]: T[P];
};
type testMyOmit = MyOmit<MyUtilTypes, 'method' | 'body'>;
// Result: { url: string }
`MyOmit` creates a new type by excluding specified keys. It is often used together with `MyExclude` and is preferred when you want to hide some properties from the original type.
Back