元素隐式具有“任何”类型,因为类型没有索引签名

时间:2017-10-27 15:29:48

标签: typescript types functional-programming typescript2.0

我正在尝试在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;

虽然我理解stringLanguage有何冲突,但我想知道如何在不改变语言结构的情况下解决这个问题。

1 个答案:

答案 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;