Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
August 17, 2021 12:14 pm GMT

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

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To