Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a fixed-length type in flow

Tags:

flowtype

I want to create a type that represents 2-character ISO country codes. Is there a simple way to create a type definition for these (or any other fixed-length item)?

Of course one approach would be an enum with the list of all the possible ones

type CountryCode = "AX" | "AL" | "DZ" | ...

But I'd love something simpler that just enforces 2-character strings.

Do I need to use dynamic type tests?

like image 512
Jamund Ferguson Avatar asked Aug 30 '16 20:08

Jamund Ferguson


1 Answers

No, Flow does not have such a feature. It doesn't really have any dependent types features other perhaps types consisting individual values.

You could use tests like if (countryCode.length === 2) { ... } like you would normally do in JS, but Flow will not refine the type of countryCode inside the if block, because there is no Flow type to represent strings of two characters.

In contrast, with actual dynamic type tests like if (countryCode !== null) Flow will know that countryCode is not null inside the if block and can use that knowledge for type checking.

Note that technically you could generate a type that contains 26*26=676 strings of uppercase characters from A to Z: "AA", "AB", ..., "ZY", "ZZ", but that's not an improvement over your implementation.

like image 173
Nikita Avatar answered Nov 15 '22 02:11

Nikita