1

So I am importing file which contains the following values (and many other likes this)

export const COLUMN_TYPES = [
  "integer",
  "string",
  "boolean",
  "datetime",
  "image",
  "images",
  "text",
  "auth_key",
  "enum_type"
];

Now, I don't want the type of the above to be Array<string> since I am sure that it is only going to contain values.

If I don't write type and just import it gives following error

Cannot find module 'src/constants' or its corresponding type declarations.

What is the best way to fix this error? using Array<string> even though our array is constant with specific values? use enums?

Alwaysblue
  • 9,948
  • 38
  • 121
  • 210
  • 2
    What type do you want it to be instead? Would `export const COLUMN_TYPES = [ ... ] as const;` suit you? – zerkms Aug 17 '20 at 18:47
  • 1
    Does this answer your question? [TypeScript array to string literal type](https://stackoverflow.com/questions/44497388/typescript-array-to-string-literal-type) – Etheryte Aug 17 '20 at 18:51

1 Answers1

2

you can have enum instead of constant array like this and you can use it as type like this

export enum COLUMN_TYPES {
  integer,
  string,
  boolean,
  datetime,
  image,
  images,
  text,
  auth_key,
  enum_type
}


var types: COLUMN_TYPES[] = [COLUMN_TYPES.auth_key, COLUMN_TYPES.boolean, /** ............. **/ ];

Example: Typescript Playground

Updated Answer for CRice

for example, you can define the statuses as enums like this

export enum ItemStatus {
  REJECTED = 2,
  REMOVED = 4,
  APPROVED = 6,
  PROCESSED = 7,
  PAYABLE = 8,
  PARTIALLY_PAID = 9,
  PAID = 10,
}

so in your item model, you will use the enum as a type of status

export interface ItemModel {
   // .......
   status: ItemStatus
}

and in component, you can import the ItemStatus and use it for example in the condition

Usage Example

import { ItemStatus } from 'path';
if(item.status === ItemStatus.PAID) {

}

or

switch(item.status) {

  case ItemStatus.REJECTED:
  break;
  case ItemStatus.REMOVED:
  break;
  case ItemStatus.APPROVED:
  break;
  case ItemStatus.PROCESSED:
  break;
  case ItemStatus.PAYABLE:
  break;
  case ItemStatus.PARTIALLY_PAID:
  break;
  case ItemStatus.PAID:
  break;

}
Ashot Aleqsanyan
  • 4,252
  • 1
  • 15
  • 27
  • Good answer though fwiw I don't much like enums in typescript. Consider adding the alternative approach outlined in zerkms comment: use the `as const` modifier on the array and continue to use string literals instead of an enum. – CRice Aug 17 '20 at 19:04
  • @CRice I just improvised, I didn't use this before. Yes, I see it, let me test one more time. – Ashot Aleqsanyan Aug 17 '20 at 19:07
  • @CRice the good things of the enums are that there will make your code more readable. for example, you can use the enums for the statuses, types and etc. – Ashot Aleqsanyan Aug 17 '20 at 19:13
  • @CRice I have updated the asnwer with the usage example – Ashot Aleqsanyan Aug 17 '20 at 19:28