ref – https://www.typescriptlang.org/docs/handbook/2/mapped-types.html
1 2 3 4 5 6 7 8 9 10 11 |
// we declare a type called OnlyBoolsAndHorses type OnlyBoolsAndHorses = { // for all keys, it must be boolean or number [key: string]: boolean | number; }; // example: const conforms: OnlyBoolsAndHorses = { del: true, rodney: 2534 } |
declare a type called AllAreBooleanProperties that takes in a type object called Type.
Then for every property in object Type, declare it to be boolean.
1 2 3 |
type AllAreBooleanProperties<Type> = { [Property in keyof Type]: boolean; }; |
Example usage, say we have an object type that has properties type () => void:
1 2 3 4 |
type FeatureFlags = { darkMode: () => void; newUserProfile: () => void; }; |
now we use our AllAreBooleanProperties type generator and create a type that says all properties must be boolean:
1 |
type FeatureOptions = AllAreBooleanProperties<FeatureFlags>; |
Thus creating a type that forces object type to have all boolean properties.
1 2 3 4 |
const tmp: FeatureOptions = { darkMode: true, newUserProfile: false } |