Which of the following best explains why interfaces are needed in TypeScript?
Think about how interfaces help with organizing and checking data shapes.
Interfaces in TypeScript specify the shape of objects. They help catch errors early by checking that objects follow the expected structure.
What will be the output of the following TypeScript code when compiled and run?
interface Person {
name: string;
age: number;
}
function greet(person: Person) {
return `Hello, ${person.name}. You are ${person.age} years old.`;
}
const user = { name: "Alice", age: 30 };
console.log(greet(user));Interfaces are only for compile-time checks and do not affect runtime objects.
The object 'user' matches the interface shape, so the function runs and prints the greeting correctly.
What error will this TypeScript code produce?
interface Vehicle {
wheels: number;
drive(): void;
}
const bike: Vehicle = {
wheels: 2
};Check if all required properties and methods of the interface are present.
The object 'bike' is missing the 'drive' method required by the Vehicle interface, causing a compile-time error.
Which option shows the correct syntax to declare an interface with a required string property 'title' and an optional number property 'year'?
Remember how optional properties are marked in TypeScript interfaces.
Option C correctly uses '?' to mark 'year' as optional. Other options have syntax errors or wrong types.
You want to create a function that accepts an object with properties 'x' and 'y' as numbers. Which interface and function definition ensure this and allow TypeScript to check the input?
Check that the function parameter type matches the interface exactly.
Option A uses the interface Point for the parameter, ensuring both 'x' and 'y' are numbers and present. Others have mismatched types or missing properties.