Flow: Using constant as type

Created on 26 Jun 2018  路  7Comments  路  Source: facebook/flow

Recently I've been trying to use flow with Redux. I have error with this snippet:

// in actions/auth/register
export const REGISTER = 'REGISTER';
export const SUCCESS_REGISTER_USER = 'SUCCESS_REGISTER_USER';

// in type declaration files
import {
  REGISTER,
  SUCCESS_REGISTER_USER
} from 'actions/auth/register';

import User from 'types/User';

export type Action =
  | {type: REGISTER, user: User}
  | {type: SUCCESS_REGISTER_USER, user: User}

However, flow doesn't complain when I change type Action to

export type Action =
  | {type: 'REGISTER', user: User}
  | {type: 'SUCCESS_REGISTER_USER', user: User}

And flow complain that Cannot use string as a type because string is a value. To get the type of a value use typeof. Does anyone know how to resolve this?

feature request

Most helpful comment

@hoangpham95 you have to declare the type of the REGISTER constant:

export const REGISTER: 'REGISTER' = 'REGISTER';

Flow could really be smarter here, but it isn't.

All 7 comments

// in actions/auth/register
export const REGISTER: 'REGISTER' = 'REGISTER';
export const SUCCESS_REGISTER_USER: 'SUCCESS_REGISTER_USER' = 'SUCCESS_REGISTER_USER';

// in type declaration files
import {
  REGISTER,
  SUCCESS_REGISTER_USER
} from 'actions/auth/register';

import User from 'types/User';

export type Action =
  | {type: typeof REGISTER, user: User}
  | {type: typeof SUCCESS_REGISTER_USER, user: User}

@jcready I thought typeof REGISTER is a string, and a random action like {type: "random stuff", user} will still pass the typecheck.

@hoangpham95 you have to declare the type of the REGISTER constant:

export const REGISTER: 'REGISTER' = 'REGISTER';

Flow could really be smarter here, but it isn't.

@jcready still doesn't fix the error

Any ideas? It's really annoying restriction from Flow!

@jcready, it's not a solution, it's a verbose workaround.

I also ran into this problem, how about this?

const register = { Register }

export type Action = {
  type: $Values<typeof register>,
}

Was this page helpful?
0 / 5 - 0 ratings