Sub topic 1
TypeScript Interfaces and Type Aliases: Describing Shapes and Choosing Between Them
Prerequisites
You should know basic TypeScript types such as string, number, and boolean. You should also be familiar with JavaScript objects and be able to run the TypeScript compiler.
How TypeScript compares shapes: structural typing
TypeScript uses structural typing. A value matches a type when it has the required structure, regardless of the type's declared name.
interface Point {
x: number;
y: number;
}
function length(p: Point): number {
return Math.sqrt(p.x * p.x + p.y * p.y);
}
const origin3d = { x: 3, y: 4, z: 5 };
console.log(length(origin3d)); // 5origin3d has the x and y properties that Point requires, so it can be passed to length. Its extra z property does not matter.
Declaring object shapes with interfaces
An interface names the expected properties and their types. It is often a clear choice for object-shaped data that may be extended later.
interface User {
id: number;
name: string;
}
function greet(user: User): string {
return `Hello, ${user.name}`;
}
console.log(greet({ id: 1, name: "Ada" }));The object literal passed directly to greet cannot contain unexpected properties. This is an excess property check. The check helps catch spelling mistakes, but structural compatibility still allows extra properties when the value is first stored in a variable.
Naming types with type aliases
A type alias gives a name to any type expression. It can name object shapes, unions, literal types, tuples, and function types.
type Result =
| { ok: true; value: string }
| { ok: false; error: Error };
function describe(result: Result): string {
return result.ok ? result.value : result.error.message;
}Interfaces primarily describe extendable object shapes. Type aliases are necessary when naming a union or combining more complex type expressions.
Optional and readonly properties
An optional property uses ? and may be absent. A readonly property can be read but not reassigned through that type.
interface User {
readonly id: number;
name: string;
email?: string;
}
const user: User = { id: 1, name: "Ada" };
user.name = "Ada Lovelace";
// user.id = 2; // Error: id is readonlyExercise
Why can origin3d be passed to a function expecting Point?
Show answer
Structural typing allows it because origin3d contains every required Point property: x and y.