I often have string literal types like this one:
const supportedLanguageTags = [
"de-at",
"de-ch",
"de-de",
"en-gb",
"en-us",
] as const;
type LanguageTag = typeof supportedLanguageTags[number];
function isSupportedLanguageTag(tag: string): tag is LanguageTag {
return (supportedLanguageTags as unknown as string[]).includes(tag);
}
Here I use an array to define the type but also to be able to check if a random string is included in the literal type.
However I really don't like the type assertion. Do you have suggestions to get rid of it?
One solution would be to use an object instead of an array like this:
const supportedLanguageTags = {
"de-at": 1,
"de-ch": 1,
"de-de": 1,
"en-gb": 1,
"en-us": 1,
};
type LanguageTag = keyof typeof supportedLanguageTags;
function isSupportedLanguageTag(tag: string): tag is LanguageTag {
return tag in supportedLanguageTags;
}
But here I don't like having to define a random value for every object property.