JonLuca
JonLuca

Reputation: 919

Make the type the values of an object in flow

I have a file that exports a static object of key/value pairs:

const.js:

// @flow

export default const DEFAULTS = {
    myDefault: 'a',
    myDefaultB: 'b',
}

I'd like to say that the type of an object in another file is one of the values in DEFAULTS

main.js:

// @flow

import DEFAULTS from './const';

type MyReturnType = {|
    defaultValue = 'a' | 'b',
|}

Looking through the flow docs it seems like $Values is what I want - however,

type MyReturnType = {|
    defaultValue = $Values<DEFAULTS>,
|}

throws a flow error. If I prefix it with typeof, it works, though.

type MyReturnType = {|
    defaultValue = $Values<typeof DEFAULTS>,
|}

Is $Values correct? It seems to me like thats just saying it's a string, not necessarily limiting it to just 'a' or 'b'.

Upvotes: 1

Views: 812

Answers (1)

Aleksey L.
Aleksey L.

Reputation: 37918

In order to $Values to resolve literal types (e.g. 'a' | 'b' instead of just string) it should be applied to frozen object:

const DEFAULTS = Object.freeze({
  a: 'a',
  b: 'b'
});

type DefaultValues = $Values<typeof DEFAULTS>;

const foo: DefaultValues = 'a'; // OK
const bar: DefaultValues = 'unexpected'; // string is incompatible with enum

Try

Upvotes: 1

Related Questions