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.

2
  • when we import, we do not have to write type in import line Commented Jul 13, 2021 at 3:47
  • I'm using import type to avoid failing ESLint's no-cycle rule because my type imports result from circular dependency. Commented Jul 13, 2021 at 7:27

2 Answers 2

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';
Sign up to request clarification or add additional context in comments.

4 Comments

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.
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.
@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?
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.
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());

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.