green
green

Reputation: 393

How to create type with constants properly with Flow in Javascript?

I am creating types for React application with Flow. I am not sure how is the right way to do this.

I want to have constant for the possible entries in the type which can I access afterwards (as enum) and I want the type to contain the constant instead of literal.

// @flow

export const CARD_TYPE = {
 firstType: 'one',
 secondType: 'two',
};

export type CardType = {
 type: CARD_TYPE,
};

I expect that I will be able to use the CARD_TYPE as constant in my components, and the CardType as type, but I get the following error:

Flow: Cannot use object literal as a type because object literal is a value. To get the type of a value use typeof.

Upvotes: 1

Views: 402

Answers (1)

wmp224
wmp224

Reputation: 447

I hope I'm understanding your question correctly. You should be able to do the following

// @flow

export const CARD_TYPE = {
 firstType: 'one',
 secondType: 'two',
};


export type CardType = $Keys<typeof CARD_TYPE>

here's a codepen of the solution with no errors

Upvotes: 2

Related Questions