Explainers

TypeScript Mapped Types: Types That Write Types

Published
Duration
Language
English

Watch on YouTube ↗

Summary

One line of TypeScript that writes your types for you: type Copy of T = { [K in keyof T]: T[K] }. This short explainer covers TypeScript mapped types: mapping modifiers (-readonly and -? for Mutable of T and a homemade Required of T), key remapping with as (TypeScript 4.1+) to generate typed getters like getName, filtering keys by returning never, and typed event handlers built from a string union.

Every snippet was checked with TypeScript 7.0.2 (tsc --noEmit --strict, zero errors).

Chapters

  1. 0:00 One line that writes types
  2. 0:15 Modifiers: -readonly and -?
  3. 0:27 Key remapping with as: typed getters
  4. 0:43 Filtering with never
  5. 0:53 Typed event handlers

Transcript

Text of the video's narration.

One line of TypeScript that writes your types for you. Type Copy of T is an object where, for every K in keyof T, the value is T of K. Same keys, same types. Even readonly and optional carry over. Now change the rules. Minus readonly strips readonly from every key: that is Mutable of T.

Minus question mark makes every key required: a homemade Required of T. Here is the wow moment. Add as, and you can rename each key. With a template literal and Capitalize, name becomes getName, and every property turns into a function that returns its type.

Typed getters, generated from one line. You can filter, too. If the value extends Function, return never, and the key is dropped. The methods disappear, the data stays. It works in real code. Take a union of event names, map each one to on plus Capitalize, and you get onClick, onFocus and onBlur, each with a typed handler. Your types can be generated, not written.

Sources

Credits and notes

  • Narrated with Phonon; motion in Remotion.

More in this series · Explainers