我正在尝试在TypeScript中实现类似Maybe.withDefault
的内容:
const locale = 'en-US'; //navigator.language
const systemLanguage:Language = withDefault(locale, 'en');
const languages = {en: <'en'>'en', mk: <'mk'>'mk', es: <'es'>'es'};
type Language = keyof typeof languages;
const withDefault = (candidate: string, def: Language): Language =>
languages[langCandidate] ? languages[langCandidate] : def;
虽然我理解string
与Language
有何冲突,但我想知道如何在不改变语言结构的情况下解决这个问题。
答案 0 :(得分:2)
您可以通过引入可以通过Language
或字符串索引的中间类型,并引入一个隐式转换languages
到该类型的中间函数来实现这一点(转换成功而不进行类型转换,因为这些类型是单向兼容的):
const languages = {en: <'en'>'en', mk: <'mk'>'mk', es: <'es'>'es'};
type Language = keyof typeof languages;
type LanguageLookup = {[n in Language | string]: Language};
function languageLookup(language: string, lookup: LanguageLookup): Language | undefined {
return lookup[language];
}
const withDefault = (candidate: string, def: Language): Language =>
languageLookup(candidate, languages) || def;