Defining Types with Typescript Omit

Scenario

We have a Todo interface.

interface Todo { 
title: string;
description: string;
completed: boolean;
createdAt: number;
}

And we also want to create a TodoPreview interface containing only the following properties.

interface TodoPreview { 
title: string;
completed: boolean;
}

In other words it omits the description and createdAtproperties from the Todo interface.

Approach

Use Omit to exclude the description and createdAt properties from Todo.

type TodoPreview = Omit<Todo, "description" | "createdAt">;

And now we can use the type.

const todo: TodoPreview = {
title: "Complete me!",
completed: false
};

Note that if we try to declare the other properties in Todo VSCode will lint the error.

Demo

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ole Ersoy

Ole Ersoy

Founder of Firefly Semantics Corporation