Lesson 9 / 26
Object Types & Interfaces
Describe the shape of an object, inline or with a reusable interface.
Inline object types
You can annotate an object's shape directly, right where it's used.
let user: { name: string; age: number } = {
name: "Ada",
age: 36,
};
user.age = "old";
// Error: Type 'string' is not assignable to type 'number'.Interfaces
An interface names a shape so you can reuse it across variables, parameters and return types.
interface User {
name: string;
age: number;
}
function printUser(u: User): void {
console.log(`${u.name} (${u.age})`);
}Why interfaces?
Any object with the right properties satisfies an interface — TS checks structure, not the class name. This is called "structural typing".