Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flowtype - string incompatible with string enum

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).

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);
}

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?

like image 683
ianastacio Avatar asked Aug 08 '16 09:08

ianastacio


1 Answers

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]);
}
like image 115
vkurchatkin Avatar answered Nov 14 '22 17:11

vkurchatkin