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;
}
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]
}
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">;
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,
}
For more details please refer official doc
Top comments (4)
Why would I need a custom omit type?
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 ☺️
It's a very good way of practicing
Thank you Ajay, I was looking for the syntax of how to exclude some keys based on condition and finally found it here. With using the construction of conditional keys like
[Key in keyof T as Key extends K ? never : Key] there is so many cool things to do.
For example, here I created a simple type to get only properties from a provided type:
type Properties<T> = {
[Key in keyof T as T[Key] extends Function ? never : Key]: T[Key]
};
Nice utility to use in serializations, for example. Thank you once again!