I want to have a TypeScript object literal constant with known but long list of properties which all have the same type. Below is the definition of the type and simplified example with only three properties.
type ContainerSize = {
height: string;
width: string;
threshold?: number;
};
const CONTAINER_SIZES = {
'/': { height: '65px', width: '220px' },
'/info': { height: '220px', width: '220px' },
default: { height: '700px', width: '500px', threshold: 480 },
} as const;
The issue with the definition above is that the property types are not ContainerSize. This can be fixed by using Record<string, ContainerSize> as the object type:
const CONTAINER_SIZES: Record<string, ContainerSize> = {
'/': { height: '65px', width: '220px' },
'/info': { height: '220px', width: '220px' },
default: { height: '700px', width: '500px', threshold: 480 },
} as const;
but now any string is a valid key and thus CONTAINER_SIZES['not-existing'] wouldn't show an error.
Is there any other way to define the object literal than writing the properties twice as in the example below?
const CONTAINER_SIZES: Record<'/' | '/info' | 'default', ContainerSize> = {
'/': { height: '65px', width: '220px' },
'/info': { height: '220px', width: '220px' },
default: { height: '700px', width: '500px', threshold: 480 },
} as const;