Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Enforce shape of object values while treating keys still as const's

I have a map of filters defined like this:

type TFiltersNext = { [key: string]: { type: 'date' | 'enum' } };

const filtersNext: TFiltersNext = {
  foo: { type: 'date' }
};

I want to define valid filter names in a type like this:

type TFilterNameNext = keyof typeof filtersNext;

However this isn’t working as this test doesn’t cause issues:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const filterName: TFilterNameNext = 'bar';

As we see, bar is not a valid filter name.

I recreated this in TS Playground here – https://www.typescriptlang.org/play/?#code/C4TwDgpgBAKgYgSwDbAgJwM4DkIA9hQC8UA3lANoDWEIAXFBsGggHYDmAuvWaJPQOQATAIap+UAD5R+EFgFcAtuIC+UZQG4AUJoDGAexaMoAM2SpMOfPXhn02PAWIlNUE3r3covCAJFi1mhqa3rCIKOhYwgoQlo5Q1CB6xl7gEEkmthYOWvqGBKbhaJHR1mHmxTEORNLG7sL86kA

If I remove the : TFiltersNext from const filtersNext: TFiltersNext = { it works, but then I lose the enforcement of the shape of the values.

Anyone know whats going on?

>Solution :

Use the satisfies keyword:

type TFiltersNext = { [key: string]: { type: 'date' | 'enum' } };

const filtersNext = {
  foo: { type: 'date' }
} satisfies TFiltersNext;

type TFilterNameNext = keyof typeof filtersNext;
const filterName: TFilterNameNext = 'fooa';

Then you’ll get error and get the explicit keys. You cannot explicitly tell the type of the object is :TFiltersNext because its keys are declared to be anything ([key: string])

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading