Interfaces
Define an interface
An interface lists required property names and types. Objects that match the shape are accepted.
interface User {
name: string;
age: number;
}
const learner: User = { name: "Ada", age: 28 };
console.log(learner.name);
Mark optional properties
A trailing ? means the property may be missing.
interface Course {
title: string;
lessons: number;
published?: boolean;
}
const draft: Course = { title: "TypeScript", lessons: 18 };
Reuse shapes in functions
Pass the interface as a parameter type so callers must provide the right fields.
function greet(user: User): string {
return `Hello, ${user.name}`;
}
console.log(greet({ name: "Sam", age: 20 }));
Interface habits
- Name interfaces after the data they describe
- Prefer interfaces for object shapes you reuse
- Type aliases (
type) also work; interfaces excel at extendable objects - Excess property checks catch typos on object literals
Comments
One comment per signed-in account. Comments are saved with this page’s URL.