Flow: Is it possible to access properties on record types?

Created on 21 Apr 2017  路  1Comment  路  Source: facebook/flow

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.

Try flow

// @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';
// --------------^
question

Most helpful comment

There are multiple options here:

  • alias literal types:
type a = 'a';
type b = 'b';
type c = 'c';
type all = a | b | c;

const z2: aa | b = 'b'; // won't work
  • assert that type is a subtype of another:
type all = 'a' | 'b' | 'c';
type some = 'aa' | 'b';

declare var some_: some;
(some_: all); // error
  • use $PropertyType. It works like you want, but instead of recordT.a you write $PropertyType<recordT, 'a'>

>All comments

There are multiple options here:

  • alias literal types:
type a = 'a';
type b = 'b';
type c = 'c';
type all = a | b | c;

const z2: aa | b = 'b'; // won't work
  • assert that type is a subtype of another:
type all = 'a' | 'b' | 'c';
type some = 'aa' | 'b';

declare var some_: some;
(some_: all); // error
  • use $PropertyType. It works like you want, but instead of recordT.a you write $PropertyType<recordT, 'a'>
Was this page helpful?
0 / 5 - 0 ratings

Related issues

iamchenxin picture iamchenxin  路  3Comments

ctrlplusb picture ctrlplusb  路  3Comments

jamiebuilds picture jamiebuilds  路  3Comments

pelotom picture pelotom  路  3Comments

Beingbook picture Beingbook  路  3Comments