Object Types and InterfacesLesson 2.1
How to type objects in TypeScript with inline types
object type annotation, property types, optional properties, excess property checking, object literal types, readonly properties
Typing objects inline
You can annotate an object's shape directly at the point of use:
let user: { name: string; age: number; isAdmin: boolean } = {
name: "alice",
age: 30,
isAdmin: false
};Optional properties
Add ? to mark a property as optional:
let config: { host: string; port?: number } = { host: "localhost" };
// port is undefined if not providedReadonly properties
let point: { readonly x: number; readonly y: number } = { x: 0, y: 0 };
point.x = 5; // Error: Cannot assign to 'x' because it is a read-only propertyExcess property checking
TypeScript rejects extra properties when you assign an object literal directly:
let user: { name: string } = { name: "alice", role: "admin" };
// Error: Object literal may only specify known propertiesThis only applies to direct assignments. Assigning through an intermediate variable bypasses the check — a subtle gotcha:
const tmp = { name: "alice", role: "admin" };
let user: { name: string } = tmp; // No error — structural check onlyInline object types are useful for one-off shapes. For reused shapes, use interfaces.
