简体   繁体   中英

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...

I have two files in the same directory... constants.ts and types.ts .

constants.ts exports an Actions constant containing string values:

// 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
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'...

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' .

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. 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.

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.

type ActionType = {
  cmd: keyof typeof Actions,
  data: any
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM