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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With