Complete the code to define an object matching the interface.
interface Person { name: string; age: number; }
const person: Person = { name: "Alice", age: [1] };The age property must be a number, so 25 is correct.
Complete the code to cause the excess property error when assigning an object literal.
interface Car { make: string; model: string; }
const myCar: Car = { make: "Toyota", model: "Corolla", [1]: 2020 };The interface Car does not include year, so adding it causes an excess property error.
To fix the error, remove or avoid adding properties not defined in the interface.
Fix the error in the code by completing the type assertion.
interface Book { title: string; author: string; }
const myBook = { title: "1984", author: "Orwell", pages: 328 } as [1];Using as Book tells TypeScript to treat the object as a Book, ignoring excess properties.
Fill both blanks to create a function that accepts an object matching the interface but allows extra properties.
interface User { username: string; email: string; }
function registerUser(user: [1]) {
console.log(user.username);
}
const newUser = { username: "john", email: "john@example.com", [2]: true };
registerUser(newUser);Using User & Record<string, any> allows extra properties.
The extra property isAdmin is allowed because of the intersection with Record<string, any>.
Fill all three blanks to create a function that accepts an object with required and optional properties, allowing excess properties.
interface Config { host: string; port?: number; }
function connect(config: [1]) {
console.log(`Connecting to ${config.host}:${config.[2] ?? 80}`);
}
const serverConfig = { host: "localhost", port: 8080, [3]: true };
connect(serverConfig);The function parameter type Config & Record<string, unknown> allows extra properties.
The optional property port is accessed safely with ?? 80 as default.
The extra property secure is allowed due to the intersection with Record<string, unknown>.