I am working with an object similar to this (demo link):
const locations = {
city: {name: 'New York'},
country: {name: 'United States'},
continent: {name: 'North America'}
} as const
My goal is to create a union type that includes all the keys used in the object:
type LocationNames = keyof typeof locations; // "city" | "country" | "continent"
In addition, I want to ensure type safety when initializing the locations
object like this (example link):
interface ILocationDetails {
name: string;
}
const locations: Record<string, ILocationDetails> = {
city: {name: 'New York'},
country: {name: 'United States'},
continent: {name: 'North America'}
} as const
While this approach provides type checking during initialization, it removes the const assertion and causes the resulting union type to default to strings:
type LocationNames = keyof typeof locations; // string
Question: Is there a way to retain both strong typing during initialization of
Record<any, ILocationDetails>
and extract all keys into a new union type?
Workaround: One workaround is to reassign the typed sites to an exported variable (example link):
const LocationsTyped: Record<LocationNames, ILocationDetails> = locations;