Lesson 4 of 15
Interfaces
Interfaces
An interface defines the shape of an object — what properties it must have and their types:
interface Point {
x: number;
y: number;
}
const origin: Point = { x: 0, y: 0 };
const p: Point = { x: 3, y: 4 };
TypeScript checks that the object has all required properties with the correct types:
const bad: Point = { x: 1 }; // Error: missing 'y'
const bad2: Point = { x: "1", y: 2 }; // Error: 'string' not assignable to 'number'
Using Interfaces as Parameters
Interfaces shine as function parameter types:
function distance(p: Point): number {
return Math.sqrt(p.x * p.x + p.y * p.y);
}
console.log(distance({ x: 3, y: 4 })); // 5
Nested Interfaces
interface Rectangle {
topLeft: Point;
bottomRight: Point;
}
Your Task
Define an interface Person with name: string and age: number. Write function introduce(p: Person): string that returns "Hi, I'm [name] and I'm [age] years old".
TypeScript loading...
Loading...
Click "Run" to execute your code.