Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get union types from array in flow?

Tags:

flowtype

I have array of text strings and I'm using it in another place. How to convert it in union types?

how to get:

type Message = 'hello world' | ...

from

const messages = ['hello world', ...]
like image 276
Kherel Avatar asked Oct 25 '25 08:10

Kherel


1 Answers

This is tricky because Flow should infer a tuple type with literal string elements for the type of messages, but instead it infers the type as Array<string>. That means that the information containing the content of each string is lost. In theory you should be able to write type Message = $ElementType<typeof messages, number>, but that does not work as of Flow v0.89.0.

What you can do is express the messages in a form where Flow does preserve literal type information, such as keys in an object, and extract both the type and the list of messages from there:

const messageMap = {
  "hello world": 1, // you can use whatever you want for the values
  "goodbye": 2
}

const messages = Object.keys(messageMap)

type Message = $Keys<typeof messageMap>
like image 184
Jesse Hallett Avatar answered Oct 28 '25 03:10

Jesse Hallett



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!