This is the code I already have:
const Locales = {
en_gb: 'en-gb',
en_us: 'en-us',
} as const
type ApiLocales = typeof Locales[keyof typeof Locales]
type DatabaseLocales = keyof typeof Locales
function databaseLanguageCodeFromString(languageString: ApiLocales): DatabaseLocales[ApiLocales] {
return {
'en-gb': 'en_gb',
'en-us': 'en_us',
}[languageString]
}
However, I'm not quite sure how it works, whether it works, will it work at runtime? My database won't accept values that don't conform to an Enum, so perhaps this isn't critical. Although, it'd be good for my code to catch problems before they reach the database.
CodePudding user response:
will it work at runtime?
TypeScript types are not available at runtime. If you want to check types of data being sent or received via network request or a similar interface there are some runtime type-checking libraries you can use to accomplish this. Zod and io-ts are some of the more popular ones.
CodePudding user response:
It'll work at runtime but your types are a bit off.
Here's the correction:
const Locales = {
en_gb: 'en-gb',
en_us: 'en-us',
} as const;
// https://stackoverflow.com/questions/70037753/record-type-reverser
type Reverser<T extends Record<PropertyKey, PropertyKey>> = { [P in keyof T as T[P]]: P; }
type ApiLocales = typeof Locales[keyof typeof Locales]
type DatabaseLocales = Reverser<typeof Locales>
function databaseLanguageCodeFromString(languageString: ApiLocales): DatabaseLocales[ApiLocales] {
return ({
'en-gb': 'en_gb',
'en-us': 'en_us',
} as const)[languageString]
}
For DatabaseLocales
, we just need to reverse Locales
, and that fixes the problem. Also, in the function, we need to mark the object with as const
as well.