I am looking to create a constant object literal in TypeScript with a long list of properties all having the same type. Here is an example definition 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 downside of the current setup is that the property types are not explicitly defined as ContainerSize
. One way to fix this is 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;
However, this approach allows any string as a valid key, leading to situations where accessing non-existing keys like CONTAINER_SIZES['not-existing']
won't throw an error.
Is there a better way to define the object literal without duplicating the properties, similar to 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;