TypeScript Tutorial

Objects & Interfaces

Defining optional properties, readonly, and extensible interfaces

What is an Interface?

In TypeScript, an Interface is a "contract" that defines the shape of an object. It's a way to name a complex group of related types so you can reuse them throughout your application.
typescript
// Define the shape of a User!
interface User {
  name: string;
  age: number;
}

// Implement it!
const u1: User = { 
    name: "Alpha", 
    age: 25 
};

Comparisons: Type Alias vs. Interface

Wait! Should you use type or interface?
FeatureInterfaceType Alias (type)
LogicBest for Objects and Classes.Best for Unions (`
ExtensibleCan be merged (Re-open anytime!).Cannot be merged.
Syntaxinterface User { ... }type User = { ... };
Best Practice: Use interface by default for all object shapes, as it leads to better error messages and is more extensible.

Optional & Readonly Properties

  • ?: Marks a property as optional (it doesn't have to exist).
  • readonly: Marks a property as read-only (it cannot be changed after it's set).
typescript
interface User {
  readonly id: number; // Cannot be changed!
  name: string;
  age?: number; // Optional! (Doesn't have to be provided)
}

const u1: User = { id: 1, name: "Alpha" };
// u1.id = 2; // ERROR: Cannot change a readonly property!

Extending Interfaces

You can build new interfaces by "stealing" properties from an existing one using the extends keyword.
typescript
interface Admin extends User {
  role: "super-admin" | "moderator";
}

const boss: Admin = { 
    id: 1, 
    name: "Alpha", 
    role: "super-admin" 
};

Summary

FeatureSyntaxBehavior
Interfaceinterface x {}Describe object shape
Optionalprop?: typeProperty might be missing
Readonlyreadonly xCannot be modified after set
Extendsinterface y extends xRe-use properties from x
Best ForDescribing object shapes, APIs, state management
Mergedinterface A can be defined twice! (They combine!)
Type SafeTS ensures you don't miss a required property!
AutocompleteGet perfect suggestions when typing object data!
Intersectiontype A & B (The non-extending way to merge!)
StandardThe preferred way to write modern React/Next.js code
LibraryMost JS libraries provide interfaces for their data!
ClassClasses can implement interfaces! (See Classes section)
ConstraintUse interfaces to "contract" your data requirements!
Index Sign.[key: string]: any (Allow ANY additional properties!)
Methodgreet(msg: string): void (Define logic in an interface!)
RecursiveAn interface can refer to itself (e.g., for Trees!)
HybridInterfaces can describe FUNCTIONS and OBJECTS at once!
ExcessTS checks for "hidden" properties you didn't define!
ToolingBuilt-in support for VS Code and other editors
RefactorRename a property, and it updates across all objects!
DocumentationInterfaces act like live documentation for your data!
SafetyPrevents "undefined" errors by catching missing keys!