Defining Types with Typescript Omit | Task

Ole Ersoy
Jun - 29  -  1 min

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 createdAt properties from the Todo interface.

Approach

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

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

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