Flow type action does work with Object refrerence

2019-08-02 06:27发布

Why does flow throw an error using an object as Reference here:

type LoadUserData = { type: actionTypes.LOAD_USER_DATA, user: User };

But when a string is used no error is thrown:

type LoadUserData = { type: "LOAD_USER_DATA", user: User };

The error that is thrown is:

Error:(8, 29) Flow: string. Ineligible value used in/as type annotation (did you forget 'typeof'?) LOAD_USER_DATA

2条回答
太酷不给撩
2楼-- · 2019-08-02 07:14

Unfortunately, Flow doesn't allow you to use constants within your type definitions. It must either be a data type or a constant value, but no variables. Therefore, you'll have to stick with the:

type LoadUserData = { type: 'LOAD_USER_DATA', user: User }

I'm assuming this is a type definition for a Redux action, in which case, Facebook's docs actually recommend this anyway!

查看更多
做自己的国王
3楼-- · 2019-08-02 07:16

You can use typeof as it suggests, but that probably won't do what you want:

const actionTypes = {
  LOAD_USER_DATA: 'foo'
}

type LoadUserData = { type: typeof actionTypes.LOAD_USER_DATA};

({type: 'bar'}: LoadUserData) // no errors

This happens because Flow infers the type of actionTypes.LOAD_USER_DATA to be string.

Unfortunately for your use case you will probably have to just write out the string literals again in the type.

查看更多
登录 后发表回答