bhylu.com

Advertisements

TypeScript Mapped Types

A mapped type visits a set of property keys and builds a related object type. It is useful for systematic transformations that would otherwise repeat the same relationship across fields.

How it works

The type below turns every field in a lot into a zero-argument reader. The implementation still has to create those functions; mapped types do not generate runtime code. Optional and readonly modifiers can be added or removed, and an as clause can remap keys. Use these tools when the transformed contract remains understandable to its consumers.

Run the code

Try in playground loads this source without running it. Choose Run when ready. The existing TypeScript 5.8.3 worker transpiles and executes one file; it does not perform full semantic type checking, load npm imports or provide DOM/Node APIs. Use the local compiler for the type contract.

For a full check, save the three downloads together in a new folder, run npm install, then npm run check. Use npm run build followed by npm start to execute the checked JavaScript with Node. The supplied project enables strict checking, indexed-access checks and exact optional properties.

Example

lesson.ts

type Readers<T> = { [K in keyof T]: () => T[K] };
type Lot = { code: string; packets: number };
const readers: Readers<Lot> = { code: () => "RD-8", packets: () => 12 };
console.log(readers.code(), readers.packets());

Expected result

RD-8 12

The code reader must return a string and the packets reader must return a number. Omitting a required reader or returning the wrong type is a checker error. A fully generic runtime builder would need a careful property enumeration and ownership contract; this example keeps construction explicit so the type transformation is the focus.