Interfaces, Types and Object Shapes
Harry
· 14 Sep 2026
· 2 views
Advertisement
Describing an object
An interface defines the shape an object must have. Functions that take that interface only accept matching objects:
interface User {
name: string;
age: number;
}
function greet(u: User): string {
return `Hello, ${u.name}`;
}
greet({ name: "Ada", age: 36 }); // OK
greet({ name: "Ada" }); // Error: age is missing
Optional and read-only members
interface Product {
id: number;
name: string;
discount?: number; // optional
readonly sku: string; // cannot be reassigned after creation
}
A ? makes a property optional; readonly prevents reassignment – great for identifiers.
Type aliases and unions
type gives a name to any type, including unions – a value that may be one of several types:
type ID = number | string; // union
type Status = "active" | "banned"; // literal union
let userId: ID = 42;
userId = "u-42"; // both allowed
let s: Status = "active"; // only these two strings
Literal unions are a lightweight, type-safe alternative to enums for a fixed set of values.
Interface vs type
Both describe object shapes and are largely interchangeable. Use an interface for object contracts you may extend or implement; use a type alias for unions, tuples and more complex compositions.
Key points
- Interfaces describe the required shape of objects.
?makes a property optional;readonlyblocks reassignment.typenames any type, including unions likenumber | string.- Prefer interfaces for object contracts, type aliases for unions and compositions.