I'm trying to construct a union type from string literals. This union type is used in a lot of places where I actually only want a subset of the literals. So I'm interested in a way to construct that subset but protect myself from typos in the types themselves.
I tried the following but ran into errors. Is there another way to do this? If not, I guess this is a feature request.
// @flow
// The superset.
type all = 'a' | 'b' | 'c';
// An inline subset, but it has a typo!
const z2: 'aa' | 'b' = 'b';
// ---------^
// What if I defined a record to hold them?
type recordT = {
a: 'a',
b: 'b',
c: 'c',
};
// It doesn't work, though.
const x: recordT.a = 'a';
const y: recordT.a | recordT.b = 'b';
// If it did, it'd be possible to point out the analagous typo below.
const z: recordT.aa | recordT.b = 'b';
// --------------^
There are multiple options here:
type a = 'a';
type b = 'b';
type c = 'c';
type all = a | b | c;
const z2: aa | b = 'b'; // won't work
type all = 'a' | 'b' | 'c';
type some = 'aa' | 'b';
declare var some_: some;
(some_: all); // error
$PropertyType. It works like you want, but instead of recordT.a you write $PropertyType<recordT, 'a'>
Most helpful comment
There are multiple options here:
$PropertyType. It works like you want, but instead ofrecordT.ayou write$PropertyType<recordT, 'a'>