[英]Getting s TS2503 when trying to use an imported string constant to constrain a typescript type literal
I'm trying to learn redux by following some examples from the internet, but I'm running into a TypeScript error that I don't know how to fix... 我正在尝试通过从互联网上获取一些示例来学习redux,但是我遇到了TypeScript错误,我不知道该如何解决...
I have two files in the same directory... constants.ts and types.ts . 我在同一目录中有两个文件... constants.ts和types.ts 。
constants.ts exports an Actions constant containing string values: constants.ts导出包含字符串值的Actions常量:
// constants.ts
export const Actions = {
ADD: 'ADD',
TOGGLE: 'TOGGLE',
};
types.ts contains an ActionType which will be used to specify the parameter type in my Redux reducer functions... it uses the Actions constant and looks like: types.ts包含一个ActionType,它将用于在Redux reducer函数中指定参数类型...它使用Actions常量,如下所示:
// types.ts
import { Actions } from "./constants";
export type ActionType = {
cmd: Actions.ADD | Actions.TOGGLE,
data: any
};
I am trying to define the ActionType.cmd property so that it can only be either 'ADD' or 'TOGGLE'... 我正在尝试定义ActionType.cmd属性,以便它只能是“ ADD”或“ TOGGLE” ...
If I write these values directly, ex: 如果我直接写这些值,例如:
cmd: 'ADD' | 'TOGGLE'
everything works fine... but when I try to use the string values defined in my Actions constant, I get a TS2503 error, saying 'Cannot find namespace Actions' . 一切正常...但是当我尝试使用在Actions常量中定义的字符串值时,出现TS2503错误,提示“找不到命名空间Actions” 。
Is this possible, or am I missing something? 这可能吗,还是我错过了什么? Please help!
请帮忙!
Since you've defined Actions
as a constant, Actions.ADD
is only available as a value, not as a type. 由于已将
Actions
定义为常量,因此Actions.ADD
仅可作为值使用,而不能作为类型使用。 Consider using an enum instead: 考虑改用枚举:
export enum Actions {
ADD = 'ADD',
TOGGLE = 'TOGGLE',
};
export type ActionType = {
cmd: Actions, // short for Actions.ADD | Actions.TOGGLE
data: any
};
The members of an enum are available as both values and literal types. 枚举的成员可以作为值和文字类型使用。
As I understand it, you can't use the value of Actions.ADD
directly as a type. 据我了解,您不能直接将
Actions.ADD
的值用作类型。
You can use typeof
to get the type of a value, and keyof
to get the keys, so the following works if the names and values of the keys are the same. 您可以使用
typeof
来获取值的类型,并可以使用keyof
来获取键,因此,如果键的名称和值相同,则可以进行以下操作。
type ActionType = {
cmd: keyof typeof Actions,
data: any
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.