Optional utility type in TypeScript
Add an utility in your TypeScript codebase that will help you write down better type definitions.
I was scaling a TypeScript definition and get to know this beautiful TypeScript feature.
Hello
I'm Vikash Kumar.
TypeScript has Omit<> | Pick<> | Partial<>
That do almost all the work I need mostly playing with Type definitions, but somewhere they are lacking behind to fulfil my desires.
Suppose, I want to make some of fields in my type definition optional.
Like this
type Config = {
name: string;
version: string;
description: string;
};
type PartialConfig = {
name: string;
version: string;
description?: string;
};
I am not going to write down always as:
type PartialConfig = Omit<Config, 'description'> & Partial<Pick<Config, 'description>>
So what I did instead:
export type Optional<T, K extends keyof T> =
Omit<T, K> & Partial<Pick<T, K>>;
Now:
type Config = {
name: string;
version: string;
description: string;
};
type PartialConfig = Optional<Config, 'description'>
Really, That simple now this Optional<> generic can be used anywhere in the codebase.
Thanks for Reading!
