Desolate Planet
Desolate Planet

Reputation: 561

How do I use constants within typescript type definitions?

I have a file in my app with a list of constants called ui-constants.ts

the contents look like as follows:

export const NO_STATUS = 'NOSTATUS';
export const DRAFT_STATUS = 'DRAFT';
export const AWAITING_TRIAGE_STATUS = 'AWAITINGTRIAGE'
export const COMPLETE_NOT_REQUIRED_STATUS = 'COMPLETENOTREQUIRED';
export const UNASSIGNED_STATUS = 'UNASSIGNED';

Elsewhere in my reactjs app, I have a file where I attempt to use this:

import * as UI_CONSTANTS from '../constants/ui-constants';

 type RequestStatus =
    | 'NOSTATUS'
    | 'DRAFT'
    | 'AWAITINGTRIAGE'
    | 'COMPLETENOTREQUIRED'
    | 'UNASSIGNED';

Now, the problem is that the application I've picked up is a bit of a mess, with constants used in some places and types used in others. What I would like to do is use the constants within the type i.e

 type RequestStatus = UI_CONSTANTS.NO_STATUS | UI_CONSTANTS.DRAFT_STATUS | UI_CONSTANTS .AWAITING_TRIAGE_STATUS | UI_CONSTANTS.COMPLETE_NOT_REQUIRED_STATUS 

Doing this results in the following error:

ui-constants"' has no exported member 'NO_STATUS'.ts(2694)

The context of this is that I have one developer that is unhappy that literal values are used across the source code where they should be constants, and other that believes typing should be used.

I'm looking at whether I can achieve the best of both worlds by defining constants and where types are used, specify those constants as values for those types.

Is this achievable or am I doing this wrong?

Upvotes: 1

Views: 1876

Answers (2)

zixiCat
zixiCat

Reputation: 1059

Try this one:

import * as UI_CONSTANTS from '../constants/ui-constants';

type RequestStatus = typeof UI_CONSTANTS[keyof typeof UI_CONSTANTS]

const a: RequestStatus = 'NOSTATUS' // OK
const b: RequestStatus = 'DRAFT' // OK
const c: RequestStatus = 'TEST' // Error

Upvotes: 2

Mudassar
Mudassar

Reputation: 598

As @kaya3 said, I would suggest you to create enum which is powerful feature of TypeScript.

export enum RequestStatus {
  NO_STATUS = 'NOSTATUS',
  DRAFT_STATUS = 'DRAFT',
  AWAITING_TRIAGE_STATUS = 'AWAITINGTRIAGE',
  COMPLETE_NOT_REQUIRED_STATUS = 'COMPLETENOTREQUIRED',
  UNASSIGNED_STATUS = 'UNASSIGNED'
}

Now you can import it any file and use as you want, so you have both value and type using enum in required file.

  import { RequestStatus } from './../constants/ui-constants'
  // to get the status, use .(dot) operator
  RequestStatus.DRAFT_STATUS // 'DRAFT'

Upvotes: 2

Related Questions