An Interest In:
Web News this Week
- March 28, 2024
- March 27, 2024
- March 26, 2024
- March 25, 2024
- March 24, 2024
- March 23, 2024
- March 22, 2024
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;}
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
Original Link: https://dev.to/ajaykumbhare/2-implement-custom-omit-type-in-typescript-2i0g
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To