Flowtype - 字符串与字符串枚举不兼容

时间:2016-08-08 09:37:35

标签: javascript string enums typechecking flowtype

我有一个来自select输入的值并且是string类型,但是我想将它传递给一个函数( updateLanguage ),该函数接收带有类型别名的字符串枚举作为参数( 语言)。

我面临的问题是Flow只允许我调用 updateLanguage 如果我明确地将我的字符串值与枚举字符串进行比较,并且我想使用像array.includes这样的数组函数

这是我的问题的代码简化:

// @flow

type SelectOption = {
    value: string
};
const selectedOption: SelectOption = {value: 'en'};

type Language = 'en' | 'pt' | 'es';
const availableLanguages: Language[] = ['en', 'pt'];

function updateLanguage(lang: Language) {
    // do nothing
}

// OK
if(selectedOption.value === 'en' || selectedOption.value === 'pt') {
  updateLanguage(selectedOption.value);
}

// FLOWTYPE ERRORS
if(availableLanguages.includes(selectedOption.value)) {
  updateLanguage(selectedOption.value);
}

运行流程v0.30.0给出以下输出:

example.js:21
 21: if(availableLanguages.includes(selectedOption.value)) {
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ call of method `includes`
 21: if(availableLanguages.includes(selectedOption.value)) {
                                    ^^^^^^^^^^^^^^^^^^^^ string. This type is incompatible with
  9: const availableLanguages: Language[] = ['en', 'pt'];
                               ^^^^^^^^ string enum

example.js:22
 22:   updateLanguage(selectedOption.value);
       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ function call
 22:   updateLanguage(selectedOption.value);
                      ^^^^^^^^^^^^^^^^^^^^ string. This type is incompatible with
 11: function updateLanguage(lang: Language) {
                                   ^^^^^^^^ string enum


Found 2 errors

如何以可伸缩的方式检查字符串值是否为枚举的一部分?

1 个答案:

答案 0 :(得分:11)

这是一个可扩展且安全的解决方案:

const languages = {
  en: 'en',
  pt: 'pt',
  es: 'es'
};

type Language = $Keys<typeof languages>;

const languageMap: { [key: string]: ?Language } = languages;

function updateLanguage(lang: Language) {
    // do nothing
}

type SelectOption = {
    value: string
};
const selectedOption: SelectOption = {value: 'en'};

if(languageMap[selectedOption.value]) {
  updateLanguage(languageMap[selectedOption.value]);
}