原本使用 redux 时,会让每一个 action 的 type 定义为一个常量,之后再引用。现在切换到 TypeScript 上反而不明白怎么定义 type 是固定字符串的类型,不是直接字面量写的,而是通过参数化引用的。
这里贴上我暂时的解决方法,只是写死成字面量,真的希望找到参数化的写法。
枚举,枚举自身可以作为类型,只允许接受枚举的值。
另外一种形式是联合类型。
比如 type CountAction = "SET_COUNT" | "SET_COLLAPSED"; 这种类型下虽然是字符串,但是只允许某个字符串。配合枚举更好。
又比如,
enum CountAction {
SET_COUNT = "SET_COUNT",
CLEAR_COUNT = "CLEAR_COUNT"
}
enum AccountAction {
SET_ACCOUNT_STAT = "SET_ACCOUNT_STAT"
}
type MyReduxAction = CountAction | AccountAction;
然后定义只能调用 MyReduxAction,以上是我纯理论的,我不是写 react 和 redux 的,只懂原理。
定义只能调用 MyReduxAction,这个说错了,是只能传递这个类型的,不是调用....
试试这个库: https://cartant.github.io/ts-action/
可以用了,现在把字符串直接量的地方都换成枚举引用了!!!
![]( https://raw.githubusercontent.com/l1nyanm1ng/file-repo/master/image/20190506145730.png)
![]( https://raw.githubusercontent.com/l1nyanm1ng/file-repo/master/image/20190506145807.png)
![]( https://raw.githubusercontent.com/l1nyanm1ng/file-repo/master/image/20190506145840.png)
十分感谢!!!!