Skip to main content

Mapped Types

Mapped types transform object types by iterating over their keys and producing new property types.

1type O = {foo: number, bar: string};2type ReadOnly = {readonly [key in keyof O]: O[key]};
Try
TypeScript comparison

Flow shares TypeScript's keyof-based iteration, homomorphic {[K in keyof T]: ...} form, and distributivity over object unions. Flow's source restrictions, exactness, and variance rules still apply.

When to use this​

Use mapped types when you need to systematically transform every property of an existing object type — for example, making all properties optional, read-only, or wrapping their values. If you only need to change a few specific properties, object type spread is simpler.

Basic Usage​

Mapped types have syntax similar to indexed object types but use the in keyword:

1type O = {foo: number, bar: string};2
3type Methodify<T> = () => T;4
5type MappedType = {[key in keyof O]: Methodify<O[key]>};
Try

In this example, MappedType has all of the keys from O with all of the value types transformed by Methoditfy<O[key]>. The key variable is substituted for each key in O when creating the property, so this type evaluates to:

{
foo: Methodify<O['foo']>,
bar: Methodify<O['bar']>,
}
= {
foo: () => number,
bar: () => string,
}

Mapped Type Sources​

We call the type that comes after the in keyword the source of the mapped type. The source of a mapped type must be a subtype of string | number | symbol:

1type MappedType = {[key in boolean]: number}; // ERROR!incompatible-typeCannot instantiate {[key in boolean]: number} [1] because boolean [2] is incompatible with string | number | symbol, so it cannot be used to generate keys for {[key in boolean]: number} [1].
Try

Typically, you'll want to create a mapped type based on another object type. In this case, you should write your mapped type using an inline keyof:

1type GetterOf<T> = () => T;2type Obj = {foo: number, bar: string};3type MappedObj = {[key in keyof Obj]: GetterOf<Obj[key]>};
Try

But you do not need to use an object to generate a mapped type. You can also use a union of string literal types to represent the keys of an object type:

1type Union = 'foo' | 'bar' | 'baz';2type MappedType = {[key in Union]: number};3// = {foo: number, bar: number, baz: number};
Try

Importantly, when using string literals the union is collapsed into a single object type:

1type MappedTypeFromKeys<Keys extends string> = {[key in Keys]: number};2type MappedFooAndBar = MappedTypeFromKeys<'foo' | 'bar'>;3// = {foo: number, bar: number}, not {foo: number} | {bar: number}
Try

If you use a type like number or string in the source of your mapped type then Flow will create an indexer:

1type MappedTypeFromKeys<Keys extends string> = {[key in Keys]: number};2type MappedFooAndBarWithIndexer = MappedTypeFromKeys<'foo' | 'bar' | string>;3// = {foo: number, bar: number, [string]: number}
Try

A source can also contain unique symbols. Each becomes a symbol-keyed property in the result. Mapped types over keyof likewise preserve the source's symbol keys:

1const id = Symbol('id');2const version = Symbol('version');3
4type Meta = {[K in typeof id | typeof version]: string};5// = {[id]: string, [version]: string}6declare const meta: Meta;7meta[id] as string; // OK8meta[Symbol()]; // ERROR: not a key of `Meta`invalid-computed-propCannot access {[symbol]: string, [symbol]: string} [1] with computed property using symbol [2].
Try

Key remapping via as ≥0.339​

Add an as clause after the source to choose a new key for each property. You can use template literal types to construct names:

1type Events = {mark: number, measure: string};2type Handlers = {3  [K in keyof Events as `on${K}`]: (event: Events[K]) => void4};5
6declare const handlers: Handlers;7handlers.onmark(1); // OK8handlers.onmeasure('start'); // OK9handlers.onmark('start'); // ERROR: the original mark value type is numberincompatible-typeCannot call handlers.onmark with 'start' bound to event because "start" [1] is incompatible with number [2].10handlers.mark; // ERROR: the key is now onmarkprop-missingCannot get handlers.mark because property mark is missing in {onmark: (event: Events["mark"]) => void, onmeasure: (event: Events["measure"]) => void} [1].
Try

Handlers has onmark and onmeasure properties. The value expression still uses the original key K. For example, Events[K] reads Events['mark'], not Events['onmark'].

The as expression can also be a conditional type or an indexed access type. It must return a valid property-key type (string | number | symbol) or return empty to omit the key. The source still follows the mapped type source rules. You cannot use an arbitrary union of objects as the source.

Filtering keys​

Return empty from the as clause to remove a property:

1type PickStrings<T> = {2  [K in keyof T as T[K] extends string ? K : empty]: T[K]3};4type Labels = PickStrings<{count: number, name: string, description: string}>;5
6declare const labels: Labels;7labels.name as string; // OK8labels.description as string; // OK9labels.count; // ERROR: the number-valued property was filtered outprop-missingCannot get labels.count because property count is missing in {description: {count: number, description: string, name: string}["description"], name: {count: numbe... [1].
Try

Remapping can preserve or produce unique-symbol keys. If the source also has symbols and you want to rename only its string keys, filter with K extends string before interpolating K:

1const id = Symbol('id');2type Events = {[id]: number, change: string};3type StringHandlers<T> = {4  [K in keyof T as K extends string ? `on${K}` : empty]: (event: T[K]) => void5};6
7declare const handlers: StringHandlers<Events>;8handlers.onchange('new'); // OK9handlers[id]; // ERROR: symbol keys were filtered outprop-missingCannot get handlers[id] because property [symbol] is missing in {onchange: (event: Events["change"]) => void} [1].
Try

Collisions and object shape​

If multiple source keys map to the same destination, Flow combines their value types into a union:

1type Source = {count: number, label: string};2type Combined = {[K in keyof Source as 'value']: Source[K]};3
4declare const combined: Combined;5combined.value as number | string; // OK6combined.value as number; // ERROR: the value can also be a stringincompatible-typeCannot cast combined.value to number because string [1] is incompatible with number [2].
Try

Without explicit property modifiers, a merged property is optional if any contributor is optional. It remains read-only if any contributor is readonly. You can omit an optional merged property, and reading it includes void in the value type. Use the property modifiers to change these attributes.

Identity remapping (as K) over an inline keyof preserves an inexact source's open shape and dictionary indexers. A nonidentity remapping produces an exact object when no destination indexer survives. Dropping every indexer and property with as empty produces {}. Do not assume that remapping an open-ended string pattern behaves the same as remapping a finite union of names.

Array and tuple restriction​

Flow does not support key remapping on array or tuple sources, even for the identity as K. The existing mapping without an as clause still works:

1type Tuple = [string, number];2type ArraySource = Array<number>;3type MappedTuple = {[K in keyof Tuple]: Tuple[K]};4type MappedArray = {[K in keyof ArraySource]: ArraySource[K]};5type RemappedTuple = {[K in keyof Tuple as K]: Tuple[K]}; // ERROR: tuple remappingunsupported-syntaxKey remapping (as) on tuple/array sources is not yet supported in mapped types.6type RemappedArray = {[K in keyof ArraySource as K]: ArraySource[K]}; // ERROR: array remappingunsupported-syntaxKey remapping (as) on tuple/array sources is not yet supported in mapped types.
Try

Adoption​

To use key remapping and signed +readonly/-readonly modifiers, set experimental.tslib_syntax=true in .flowconfig and use Flow and flow-parser 0.339.0+ and Prettier 3.10.0+ with its built-in flow parser.

Distributive Mapped Types​

When the mapped type uses an inline keyof or a type parameter bound by keyof Flow will distribute the mapped type over unions of object types.

For example:

1// This mapped type uses keyof inline2type MakeAllValuesNumber<O extends {...}> = {[key in keyof O]: number};3type ObjWithFoo = {foo: string};4type ObjWithBar = {bar: string};5
6type DistributedMappedType = MakeAllValuesNumber<7  | ObjWithFoo8  | ObjWithBar9>; // = {foo: number} | {bar: number};10
11// This mapped type uses a type parameter bound by keyof12type Pick<O extends {...}, Keys extends keyof O> = {[key in Keys]: O[key]};13type O1 = {foo: number, bar: number};14type O2 = {bar: string, baz: number};15type PickBar = Pick<O1 | O2, 'bar'>; // = {bar: number} | {bar: string};
Try

Distributive mapped types will also distribute over null and undefined:

1type Distributive<O extends ?{...}> = {[key in keyof O]: O[key]};2type Obj = {foo: number};3type MaybeMapped = Distributive<?Obj>;// = ?{foo: number}4null as MaybeMapped; // OK5undefined as MaybeMapped; // OK6({foo: 3}) as MaybeMapped; // OK
Try

Property Modifiers​

Adding variance and optionality​

You can add readonly or writeonly variance modifiers and the optionality modifier ? in mapped types:

1type O = {foo: number, bar: string}2type ReadOnlyPartialO = {readonly [key in keyof O]?: O[key]}; // = {readonly foo?: number, readonly bar?: string};
Try

Adding and removing readonly ≥0.339​

+readonly works like plain readonly, making every output property read-only. -readonly removes a source property's readonly modifier. An already-mutable property stays mutable:

1type ReadOnly<T> = {+readonly [K in keyof T]: T[K]};2type Mutable<T> = {-readonly [K in keyof T]: T[K]};3type Settings = {volume: number};4
5declare const readOnly: ReadOnly<Settings>;6readOnly.volume as number; // OK7readOnly.volume = 1; // ERROR: the property is read-onlycannot-writeCannot assign 1 to readOnly.volume because property volume is not writable.8
9declare const mutable: Mutable<ReadOnly<Settings>>;10mutable.volume as number; // OK11mutable.volume = 1; // OK: readonly was removed
Try

You can combine -readonly with key remapping and use the existing -? modifier to remove optionality:

1type MutableRequired<T> = {-readonly [K in keyof T as K]-?: T[K]};2type Settings = {readonly volume?: number};3
4declare const settings: MutableRequired<Settings>;5settings.volume as number; // OK: the property is required6settings.volume = 1; // OK: the property is mutable7({}) as MutableRequired<Settings>; // ERROR: volume is now requiredincompatible-typeCannot cast object literal to MutableRequired<Settings> because property volume is missing in object literal [1] but exists in {volume: number} [2].
Try

These modifiers transform types, not runtime objects. They do not freeze, unfreeze, or copy an object. Removing readonly does not let you assign a read-only value directly to a mutable type. You still need to provide a value compatible with the result.

-readonly does not remove writeonly. If the value expression uses T[K], the input properties must still be readable:

1type Mutable<T> = {-readonly [K in keyof T]: T[K]};2type Output = {writeonly value: number};3
4declare const output: Mutable<Output>; // ERROR: T[K] cannot read the input propertycannot-readCannot instantiate Mutable because an index signature declaring the expected key / value type is not readable.5output.value as number; // ERROR: the property is still write-onlycannot-readCannot get output.value because property value is not readable.6output.value = 1; // OK: writes remain allowed
Try

Adding and removing writeonly ≥0.339​

+writeonly works like plain writeonly, making every output property write-only. -writeonly removes write-only variance, making those output properties read-write. It does not remove an existing readonly modifier.

1// Add writeonly to readable input properties.2type WriteOnly<T> = {+writeonly [K in keyof T]: T[K]};3type Settings = {volume: number};4declare const writeOnly: WriteOnly<Settings>;5writeOnly.volume as number; // ERROR: write-onlycannot-readCannot get writeOnly.volume because property volume is not readable.6writeOnly.volume = 1; // OK7
8// Remove writeonly without reading a write-only input property.9type ReadWrite<T> = {-writeonly [K in keyof T]: number};10declare const readWrite: ReadWrite<WriteOnly<Settings>>;11readWrite.volume as number; // OK12readWrite.volume = 1; // OK
Try

Removing writeonly affects output modifiers, not what the value expression can read. T[K] still cannot read a write-only input property, so ReadWrite intentionally uses number instead.

Removing optionality with -?​

The ? modifier makes every property optional. Prefixing it with - does the opposite: -? removes optionality, turning every optional property into a required one. This works like the Required<T> utility type.

1type O = {foo: number, bar?: string};2type RequiredO = {[key in keyof O]-?: O[key]}; // = {foo: number, bar: string}3({foo: 1}) as RequiredO; // ERROR: bar is now requiredincompatible-typeCannot cast object literal to RequiredO because property bar is missing in object literal [1] but exists in {bar: string, foo: O["foo"]} [2].
Try

-? only clears the optionality of properties that were optional in the source. It does not strip void or undefined from a value type that was already required:

1type T = {a: string | void};2type Mapped = {[K in keyof T]-?: T[K]};3declare const m: Mapped;4m.a as string | void; // OK: `a` was not optional, so its value type is unchanged5m.a as string; // ERROR: void is still part of the value typeincompatible-typeCannot cast m.a to string because void [1] is incompatible with string [2].
Try

-? also works on tuple inputs, where it makes elements no longer optional:

1type Tuple = [a: string, b?: number, c?: boolean];2type AllRequired = {[K in keyof Tuple]-?: Tuple[K]};3(['']) as AllRequired; // ERROR: elements 1 and 2 are now requiredinvalid-tuple-arityCannot cast array literal to AllRequired because array literal [1] has 1 element but [a: Tuple[0], b: number, c: boolean] [2] has 3 elements.4declare const t: AllRequired;5t as [string, number, boolean]; // OK
Try

Mapped Type on Arrays​

Mapped type also works on array or tuple inputs. If the mapped type is in the form of

{[K in keyof <type_1>]: <type_2>}

then type_1 is allowed to be an array or tuple type.

This feature will be especially useful if you want to map over elements of a tuple:

1type Tuple = [readonly a: number, b?: string];2type MappedTuple = {[K in keyof Tuple]: Tuple[K] extends number ? boolean : string};3const a: MappedTuple[0] = true;4const b: MappedTuple[1] = '';5'' as MappedTuple[0] // errorincompatible-typeCannot cast empty string to MappedTuple[0] because "" [1] is incompatible with boolean [2].6false as MappedTuple[1] // errorincompatible-typeCannot cast false to MappedTuple[1] because false [1] is incompatible with string [2].7declare const mapped: MappedTuple;8mapped[0] = true; // error: cannot-writecannot-writeCannot assign true to mapped[0] because tuple element at index 0 [1] labeled a is not writable.
Try

Property modifiers apply to the elements of an array input. Variance modifiers change the variance of each tuple element, and readonly turns an array into a ReadonlyArray. Arrays cannot be made write-only.

1type Tuple = [readonly a: number, b?: string];2type Supported1 = {[K in keyof Tuple]?: string};3type Supported2 = {readonly [K in keyof Tuple]: string};4type Supported3 = {writeonly [K in keyof Tuple]: string};5type Supported4 = {readonly [K in keyof Array<number>]: string};6type Unsupported = {writeonly [K in keyof Array<number>]: string}; // Errorinvalid-mapped-typeMapped Types do not yet support write-only variance annotations on array inputs.
Try

Adoption​

To use mapped types, you need to upgrade your infrastructure so that it supports the syntax:

  • prettier: 3
  • babel with flow-parser/babel-plugin. See our Babel guide for setup instructions.
  • eslint with flow-eslint. See our ESLint guide for setup instructions.

See Also​