javascript - Flowtype - string incompatible with string enum -


i have value comes select input , of type string, want pass function (updatelanguage) receives argument string enum type alias (language).

the problem i'm facing flow allows me call updatelanguage if explicitly compare string value enum strings , want use array function array.includes.

this code simplification of 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) {     // 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 following output:

example.js:21  21: if(availablelanguages.includes(selectedoption.value)) {         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ call of method `includes`  21: if(availablelanguages.includes(selectedoption.value)) {                                     ^^^^^^^^^^^^^^^^^^^^ string. type incompatible   9: const availablelanguages: language[] = ['en', 'pt'];                                ^^^^^^^^ string enum  example.js:22  22:   updatelanguage(selectedoption.value);        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ function call  22:   updatelanguage(selectedoption.value);                       ^^^^^^^^^^^^^^^^^^^^ string. type incompatible  11: function updatelanguage(lang: language) {                                    ^^^^^^^^ string enum   found 2 errors 

how can check string value part of enum in scalable manner?

here scalable , 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) {     // nothing }  type selectoption = {     value: string }; const selectedoption: selectoption = {value: 'en'};  if(languagemap[selectedoption.value]) {   updatelanguage(languagemap[selectedoption.value]); } 

Comments

Popular posts from this blog

Spring Boot + JPA + Hibernate: Unable to locate persister -

go - Golang: panic: runtime error: invalid memory address or nil pointer dereference using bufio.Scanner -

c - double free or corruption (fasttop) -