TypeScript enums cannot be used as a value when imports using the `import type` declaration

Viewed 1171

Version Information

TypeScript v4.1.3 Node.js v10.23.1 linux/amd64

https://replit.com/@AnmSaiful/ts-import-type-enum

Code

// ---- enums.ts ----
export enum Sex {

  Male    = "male",
  Female  = "female",

}

// ---- type.ts ----
export * as Enum from "./enums";

// ---- index.ts ----
import type { Enum } from "./type";

function enumTest(): Enum.Sex {

  return Enum.Sex.Male;

}

console.log( enumTest() );

Actual behavior

It does not allow using Enum from the composed imported type and says:

'Enum' cannot be used as a value because it was imported using 'import type'.

Expected behavior

It should allow using Enums from the imported type.

2 Answers

TS 3.8 add Type-Only Imports and Export feature.

import type only imports declarations to be used for type annotations and declarations. It always gets fully erased, so there’s no remnant of it at runtime.

Just import the enum like this:

import { Enum } from './type';

just fixed your issue in below link https://replit.com/@aMITrAI11/ts-import-type-enum#index.ts

  • enums.ts
export enum Sex {
  Male    = "male",
  Female  = "female",
}
  • type.ts
export * as Enum from "./enums";
  • index.ts
import { Enum } from "./type";

function enumTest() {
  return Enum.Sex.Male;
}

console.log(enumTest());
Related