问题描述
我有一个来自select输入的值并且是string类型,但是我想将它传递给一个函数( updateLanguage ),该函数接收带有类型别名的字符串枚举作为参数( 语言)。
I have a value that comes from a select input and is of type string, however I want to pass it into a function (updateLanguage) that receives as argument a string enum with a type alias (Language).
我面临的问题是Flow只允许我调用 updateLanguage 如果我明确地将我的字符串值与枚举字符串进行比较而我想要使用像array.includes这样的数组函数。
The problem I'm facing is that Flow only allows me to call updateLanguage if I explicitly compare my string value with the enum strings and I want to use an array function like array.includes.
这是我的问题的代码简化:
This is a code simplification of my problem:
// @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给出以下输出:
running flow v0.30.0 gives the following output:
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
如何以可伸缩的方式检查字符串值是否为枚举的一部分?
How can I check that the string value is part of the enum in a scalable manner?
推荐答案
这是一个可扩展且安全的解决方案:
Here is a scalable and safe solution:
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]);
}
这篇关于Flowtype - 字符串与字符串枚举不兼容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!