Mapped types help build types that are based off another type. A mapped type is a generic type which uses in keyof
to iterate through the keys of one type to create another.
They build off of [[20230403122631-index-signature-ts]].
In the following snippet, in keyof
uses keyof
to generate a union of all keys in Type
. These are then assigned as properties (e.g. keys in a key/value pair) inside of OptionsFlags
.
type OptionsFlags<Type> = {
[Property in keyof Type]: boolean;
};
type FeatureFlags = {
darkMode: () => void;
newUserProfile: () => void;
};
type FeatureOptions = OptionsFlags<FeatureFlags>;
// ^ = type FeatureOptions = {
// darkMode: boolean;
// newUserProfile: boolean;
// }
[[20210331123346-keyof-typescript]] [[20210610110122-indexed-access-types]]