gpt4 book ai didi

javascript - 如何使用常量值作为流类型文字?

转载 作者:行者123 更新时间:2023-11-30 20:51:27 25 4
gpt4 key购买 nike

我是第一次尝试使用 FlowType,在将常量值分配为类型文字时遇到了麻烦。如何更改以下内容以防止在常量定义和类型声明中使用相同的字符串值?

// @flow
export const INITIAL = 'INITIAL'
export const LOADING = 'LOADING'
export const LOADED = 'LOADED'
export const FAILED = 'FAILED'

export type State = 'INITIAL' | 'LOADING' | 'LOADED' | 'FAILED'

最佳答案

简短回答:你不能(AFAIK)

长答案:您应该重构您的程序以摆脱这些常量。如果你看看这些常量的好处(即 What is the point of the constants in redux? )

  • It helps keep the naming consistent because all action types are gathered in a single place.

  • Sometimes you want to see all existing actions before working on a new feature. It may be that the action you need was already added by somebody on the team, but you didn’t know.

  • The list of action types that were added, removed, and changed in a Pull Request helps everyone on the team keep track of scope and implementation of new features.

  • If you make a typo when importing an action constant, you will get undefined. This is much easier to notice than a typo when you wonder why nothing happens when the action is dispatched.

所有相同的事情都可以用变体类型来实现。

如果您使用的是 redux,您可以看到它们如何使用 flow in the docs about using redux with flow 消除常量:

// @flow

type State = { +value: boolean };

type FooAction = { type: "FOO", foo: boolean };
type BarAction = { type: "BAR", bar: boolean };

type Action = FooAction | BarAction;

function reducer(state: State, action: Action): State {
switch (action.type) {
case "FOO": return { ...state, value: action.foo };
case "BAR": return { ...state, value: action.bar };
default:
(action: empty);
return state;
}
}

这不仅可以确保您没有打错字等等,而且最后的 (action: empty) 可以确保您处理所有情况。

关于javascript - 如何使用常量值作为流类型文字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48132147/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com