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:
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])