Sikau

TypeScript · Day 18 · about 25 min

Types from values

typeof, ReturnType and satisfies.

Don't write it twice

If you already have a config object or a function, you can derive types *from* them instead of writing the same shape again. One source of truth, no drift.

Deriving types

const defaults = { theme: "light", fontSize: 16, sound: true };
type Settings = typeof defaults;

function createUser(name: string) {
  return { name, joined: new Date(), badges: [] as string[] };
}
type NewUser = ReturnType<typeof createUser>;

const routes = {
  home: "/",
  profile: "/profile",
} satisfies Record<string, string>;
type RouteName = keyof typeof routes;
const r: RouteName = "profile";

The rest of this lesson

  • Types that follow your dataexplain
  • satisfies: check without losing detailexplain
  • What's the type?predict
  • keyof typeofpredict
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 24 lessons of TypeScript