typestar

Object types in TypeScript

Optional, readonly, index signatures, and excess property checks.

interface Step {
  readonly idx: number;
  title: string;
  stars?: number;
  [extra: string]: unknown;
}

const step: Step = { idx: 0, title: "Literal types", note: "extra allowed" };

function summarize({ idx, title, stars = 0 }: Step): string {
  return `${idx} ${title} ${stars}`;
}

interface Strict {
  slug: string;
}

const source = { slug: "basics", steps: 26 };
const strict: Strict = source; // fine: not a fresh literal
// const inline: Strict = { slug: "basics", steps: 26 }; // excess property

console.log(summarize(step), strict.slug);

How it works

  1. ? makes a property optional; readonly blocks assignment.
  2. An index signature types the keys you did not name.
  3. A fresh object literal is checked for excess properties.

Keywords and builtins used here

The run, in numbers

Lines
22
Characters to type
539
Tokens
120
Three-star pace
95 tpm

At the three-star pace of 95 tokens a minute, this run takes about 76 seconds.

Type this snippet

Step 2 of 5 in Objects & interfaces, step 12 of 23 in Types & annotations.

← Previous Next →