Objects to unions converter
See original GitHub issueLet’s say we have a dictionary:
const FEATURES = {
SORTING: 'Sorting',
FILTERING: 'Filtering',
REORDERING: 'Reordering',
};
It can be used like this:
const features = [];
// or it can be a method of a class like "addFeature"
features.push(FEATURES.FILTERING);
I want to say to my features
array that it can accept values of the FEATURES
object only. But in order to avoid creating a separate union type and support (possible) changes there and in FEATURES object, I’d like to collect values from the object and keep them as a union type. Thus if it is necessary to add/remove value, it can be done in only one place - in the FEATURES
object.
To achieve this goal, in TypeScript it is necessary to define such monstrous type:
const FEATURES = {
SORTING: 'Sorting',
FILTERING: 'Filtering',
REORDERING: 'Reordering',
// 1. const assertions
} as const;
// 2. if we have a lot of such dictionaries, we have to repeat this stuff every time
type Feature = (typeof FEATURES)[keyof typeof FEATURES];
// if we want to get union type of keys
// type FeatureKeys = keyof typeof FEATURES;
const features: Feature[] = [];
// OK
features.push(FEATURES.FILTERING);
/*
Should throw a type error
Argument of type '"foo"' is not assignable to parameter of type
'"Sorting" | "Filtering" | "Reordering"'.
*/
features.push('foo')
Are there any thoughts of optimizing this type generation to avoid repeating such boilerplate in Hegel? Like a help function or something.
And I’d like to know if it is a common thing to work with dictionaries this way or not. Because I’m new to strong type checking and maybe I think the wrong way here…
Thanks in advance.
Issue Analytics
- State:
- Created 3 years ago
- Reactions:1
- Comments:6 (4 by maintainers)
Top GitHub Comments
@vasilii-kovalev i have reported
Values
type issue separately https://github.com/JSMonk/hegel/issues/269this works perfectly fine you don’t need to repeat anything …
try
you just need to use either
Object.freeze
orimmutableId
to achieve same result asas const
in typescript.