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

2

9

πŸ•— 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.

Limited answered 13/7, 2021 at 2:39 Comment(2)
when we import, we do not have to write type in import line – Friction
I'm using import type to avoid failing ESLint's no-cycle rule because my type imports result from circular dependency. – Limited
C
5

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';
Champignon answered 13/7, 2021 at 4:18 Comment(4)
I'm using import type to avoid failing ESLint's no-cycle rule because my type imports result from circular dependency. It is normal because the type definition file uses the class file (for the instance type), and class file uses the type definition file. – Limited
Currently, I'm using plain objects as const along with typeof Obj[ keyof typeof Obj] as a workaround. Hopefully, TS will solve the enum issue soon. – Limited
@A.N.M.SaifulIslam A simple way to solve circular dependency: A->B, B->A, create another file C, A->C, B->C. What stops you to do this? – Champignon
There are a lot of such circular dependencies (just for types) and just to get rid of this issue creating a lot of additional files for a single purpose is meaningless. I hope TS will natively support it shortly. – Limited
F
2

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());
Friction answered 13/7, 2021 at 3:47 Comment(1)
I'm using import type to avoid failing ESLint's no-cycle rule because my type imports result from circular dependency. It is normal because the type definition file uses the class file (for the instance type), and class file uses the type definition file. – Limited

© 2022 - 2024 β€” McMap. All rights reserved.