流类型的奇怪问题

时间:2019-09-29 19:17:00

标签: javascript reactjs flowtype

在我的React应用程序中,我试图使所有内容都能与Flow的类型检查一起正常工作。我遇到了一个我不知道的有趣情况。以下是相关代码:

// @flow
export const UPDATE_SESSION_PROP: string = 'UPDATE_SESSION_PROP';

// This fails
type UserEmailAction = {type: UPDATE_SESSION_PROP,
                        propName: 'currentUserEmail',
                        payload: string};

// But this works
type UserEmailAction = {type: 'UPDATE_SESSION_PROP',
                        propName: 'currentUserEmail',
                        payload: string};

来自流程的错误是:Cannot use string as a type because string is a value. To get the type of a value use 'typeof'.Flow(InferError)

以上两个type语句是否等效?

1 个答案:

答案 0 :(得分:0)

就像错误指出的一样,您不能使用值作为类型。您可以做的就是这样。

export type UPDATE_SESSION_PROP = 'UPDATE_SESSION_PROP';

// This works
type UserEmailAction = {type: UPDATE_SESSION_PROP,
                        propName: 'currentUserEmail',
                        payload: string};

第二版的实现实际上具有不同的含义。如果表示您将'UPDATE_SESSION_PROP'设为type的唯一可接受值

//This works becuase `UPDATE_SESSION_PROP` is considered Literal Type
type UserEmailAction = {type: 'UPDATE_SESSION_PROP',
                        propName: 'currentUserEmail',
                        payload: string};

Literal Type - Flow

相关问题