TSTypeScript
BeginnerLesson 4 of 15

Objects, Interfaces & Type Aliases – TypeScript

Describing the shape of objects – optional, read-only and extensible.

An interface describes the shape of an object: which properties it has and which types they have. With ? properties are optional, with readonly they are immutable after creation.

interface Nutzer {
  readonly id: number;
  name: string;
  email?: string;
}

const ada: Nutzer = { id: 1, name: "Ada" };
ada.name = "Ada Lovelace";       // allowed
// ada.id = 2;                   // Error: Cannot assign to 'id' because it is a read-only property.
// const x: Nutzer = { id: 2 };  // Error: Property 'name' is missing

function zeige(n: Nutzer): string {
  return n.name + (n.email ? " <" + n.email + ">" : "");
}
console.log(zeige(ada));

TypeScript typing is structural: only the shape counts, not the name. Any object with the matching properties fits – even without implements. Only for a direct literal does the compiler additionally check for excess properties (protection against typos).

const gast = { id: 9, name: "Gast", eingeloggt: false };
const n1: Nutzer = gast;         // ok: additional properties are allowed

// const n2: Nutzer = { id: 9, name: "Gast", eingeloggt: false };
// Error: Object literal may only specify known properties

With type you give names to arbitrary types. You extend interfaces with extends and combine types with & (intersection). For dictionaries with arbitrary keys there are index signatures and Record:

interface Admin extends Nutzer {
  rechte: string[];
}
type MitZeit = { erstellt: Date };
type ProtokollNutzer = Nutzer & MitZeit;

const chef: Admin = { id: 2, name: "Grace", rechte: ["alles"] };
console.log(chef.rechte.length);

const punkte: Record<string, number> = { ada: 10, bob: 7 };
punkte["cleo"] = 12;
const woerter: { [wort: string]: number } = {};   // equivalent
TipRule of thumb: interface for object shapes and public APIs (extensible), type for everything else – unions, tuples, function types, computed types. In practice the two are mostly interchangeable.