Task 2: Given multiple Todo interface declarations below, explain what happens when they are present in the same scope. Discuss how TypeScript treats them and fill in the `myTodo` object to satisfy the merged Todo interface requirements. ```typescript interface Todo { title: string; dueDate: Date; } interface Todo { description: string; completed: boolean; } interface Todo { priority: 'high' | 'medium' | 'low'; completed: string; } const myTodo: Todo = {}; ```
sobes.tech AI
Answer from AI
In TypeScript, when declaring multiple interfaces with the same name, they are merged (declaration merging). All properties from all interfaces are combined into a single resulting interface.
In this example, three interfaces named Todo are declared in the same scope, so the final interface will contain all properties from all three declarations.
However, there is a conflict: two interfaces declare a property completed, but with different types — boolean and string. TypeScript cannot merge properties with the same name but different types, and will produce an error.
To fix this, you should unify the types of completed or use a union type, for example:
interface Todo {
title: string;
dueDate: Date;
}
interface Todo {
description: string;
completed: boolean | string; // union of types
}
interface Todo {
priority: 'high' | 'medium' | 'low';
}
const myTodo: Todo = {
title: "Do homework",
dueDate: new Date('2024-07-01'),
description: "TypeScript homework",
completed: false, // or "yes"
priority: 'high'
};
If left as is, TypeScript will give an error due to the conflicting types of completed.
Summary:
- Interfaces with the same name are merged.
- Properties with the same name must have compatible types.
- In the
myTodoobject, you need to specify all properties from the merged interface.