Explainers · Short

One TypeScript line that writes your types

Published
Duration
Language
English

Watch on YouTube ↗

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