typestar

Reading types off values in TypeScript

typeof lifts a value's type; ReturnType and InstanceType go further.

const defaults = {
  theme: "default",
  seconds: 60,
  langs: ["ts", "go"],
};

type Defaults = typeof defaults;
type LangList = Defaults["langs"];

class Session {
  constructor(public lang: string) {}
  best(): number {
    return 104;
  }
}

type SessionType = InstanceType<typeof Session>;
type BestReturn = ReturnType<Session["best"]>;

function configure(overrides: Partial<Defaults>): Defaults {
  return { ...defaults, ...overrides };
}

const session: SessionType = new Session("ts");
const best: BestReturn = session.best();
const langs: LangList = ["ts"];
console.log(configure({ seconds: 300 }).seconds, best, langs.length);

How it works

  1. typeof value in a type position is the value's type.
  2. InstanceType<typeof Class> is what new produces.
  3. This keeps one source of truth: the value.

Keywords and builtins used here

The run, in numbers

Lines
27
Characters to type
619
Tokens
155
Three-star pace
100 tpm

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

Type this snippet

Step 2 of 4 in Reading types, step 6 of 20 in Generics.

← Previous Next →