DEV Community

Cover image for 2. Implement custom Omit Type in TypeScript
Ajay kumbhare
Ajay kumbhare

Posted on

2. Implement custom Omit Type in TypeScript

Implement Omit<Type, Keys>

Constructs a type by picking all properties from Type and then removing Keys.

interface Todo {
    title: string;
    description: string;
    completed: boolean;
}
Enter fullscreen mode Exit fullscreen mode

If you see the above interface it has 3 properties title, description, and completed. If you want to remove title key from that interface then you can use the Omit utility type. But here I am going to create a custom Omit type that will do the same thing as the Omit utility type.

type CustomOmit<T,K extends keyof T> = {
   [Key in keyof T as Key extends K ? never : Key] : T[Key]
}
Enter fullscreen mode Exit fullscreen mode

If you see the above code snippet which expects Type and Keys. Omit will only remove keys from the Type or Interface which we are passing that's why I have return K extends keyof T. and later we just need to check key is available in K if it's available we will return never else will return keyValue pair.

type TodoPreview = Omit<Todo, "title">;
type TodoPreviewCustomOmit = CustomOmit<Todo, "title">;
Enter fullscreen mode Exit fullscreen mode

Above both snippets will work the same and it will pick all key/value except title key from Todo type.

For Ex.

const todo: TodoPreviewCustomOmit = {
    description: string,
    completed: boolean,
}
Enter fullscreen mode Exit fullscreen mode

For more details please refer official doc

Discussion (3)

Collapse
jln profile image
JLN

Why would I need a custom omit type?

Collapse
ajaykumbhare profile image
Ajay kumbhare Author

You don't need but in some cases if you want to create some custom types based on your requirement then it will help you to get idea how you can implement it.

P.S. I'm practicing typescript so I can enhanced my skills day by day ☺️

Collapse
guitarino profile image
Kirill Shestakov

It's a very good way of practicing