Exporting enum in TypeScript declaration file (`.d.ts`) results in a "Unable to resolve" error

yesterday I was updating an enum in our app.d.ts file, which contains most of the app-specific types.

The contents of the file are as follows:

// app.d.ts
export module App
{
    // … more definitions

    enum MyEnum
    {
        A,
        B,
        C,
        D
    }
}

Everything was compiling correctly. However, when attempting to use the enum in another file like this:

// a.ts
import {App} from "./app";

let something = App.MyEnum.A;

TypeScript started giving errors about not being able to resolve the file app.d.ts.

https://i.sstatic.net/RqXVo.png

After much investigation and consulting the documentation, I came across this interesting disclaimer:

Enums are real objects that exist at runtime

This led me to move MyEnum from app.d.ts to its own file MyEnum.ts, where it needed to be explicitly exported for things to work smoothly:

// MyEnum.ts
export enum MyEnum
{
    A,
    B,
    C,
    D
}
// a.ts
import {MyEnum} from "./MyEnum";

let something = MyEnum.A;

So my question now is: Could this issue be related to TypeScript not directly substituting enum values with constants (unless using const enum), but rather treating them as persistent objects? And since .d.ts files get discarded during compilation into JavaScript, could this be causing the unexpected error message?

Answer №1

After encountering the exact error myself and finding your question to be incredibly helpful in resolving it promptly (thank you!), I can confidently confirm that exporting/importing enums from .d.ts files is not a viable solution and will result in this somewhat deceptive error message.

However, a successful workaround involves placing a .ts file with the same name in the corresponding location. For instance, if you have app.d.ts, alongside it should be app.ts within the same directory. This method allows for importing the enum without requiring any modifications to the import statement. You can still utilize import { MyEnum } from "./app"; in your specific scenario.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieve the IP Address using Express and GraphQL

Seeking assistance here! I recently made the switch from using rest to gql, but encountered an issue along the way. In my previous setup with rest, I was able to retrieve the user's IP address using req.ip. However, when trying to implement this in th ...

Limit the exposure of Jest globals in TypeScript to specific files

After including @types/jest in my package.json file, TypeScript and VS Code now consider all .ts files to have additional global variables such as test, describe, expect, afterAll, afterEach, and beforeEach. Is there a way to specify that these globals sho ...

"Using TypeScript: How to effectively wait for the completion of the array.sort

Need to implement a loading screen in Angular until an array is sorted. Solution provided below: this.isSorting = true; this.array = this.array.sort((a,b) => a.totlaTime - b.totalTime); this.isSorting = false; The issue faced is when isSorting is set t ...

Steps for Adding a JSON Array into an Object in Angular

Here is a JSON Array that I have: 0: {name: "Jan", value: 12} 1: {name: "Mar", value: 14} 2: {name: "Feb", value: 11} 3: {name: "Apr", value: 10} 4: {name: "May", value: 14} 5: {name: "Jun", value ...

Make sure to wait for the observable to provide a value before proceeding with any operations involving the variable

Issue with handling observables: someObservable$.subscribe(response => this.ref = response); if (this.ref) { // do something with this.ref value } ERROR: this.ref is undefined How can I ensure that the code relying on this.ref only runs after ...

Telegram Bot does not have the ability to be constructed in TypeScript

Why am I encountering this error message: TypeError: node_telegram_bot_api_1.default is not a constructor This is the TypeScript code snippet I have written: import * as dotenv from 'dotenv'; dotenv.config({ path: __dirname + '/.env&ap ...

Strategies for sending arguments to a TypeScript function from an HTML document

When I fetch my list of users as a JSONArray, I want to display the data of each user when their name is clicked. However, I am encountering difficulty passing the user's ID into the function. <ng-container *ngFor = "let user of users"> ...

What are some alternatives to using multiple slot transclution in an Angular 1.5 component?

In the process of constructing a panel component using angular 1.5, I am looking to embed some markup into this template (which has been simplified): <div class="panel"> <h1>{{ $ctrl.title }}</h1> <div ng-transclu ...

Experiencing constant errors with axios requests in my MERN Stack project using a Typescript Webpack setup

Hey there, I'm in need of some help! I've been working on a MERN Stack project and have set up Webpack and Babel from scratch on the frontend. However, every time I send a request to my Node Server, I keep getting an error message back. Can anyon ...

Custom Map Typescript Interface

Here is the structure of my interface: export interface IMyMap { [index: string]: RefObject<HTMLElement>; } This interface was created following the guidelines in the documentation: Indexable Types I am trying to implement this interface in a Re ...

What is the syntax for assigning a public variable within a TypeScript function?

I am finding it challenging to assign a value to a public variable within another function. I seem to be stuck. export class MyClass{ myVar = false; myFunction(){ Module.anotherFunction(){ this.myVar = true; } } } ...

Creating a Loading Sign with a Button Component in React

Request Description: In my form, I have a button that triggers a submission to the backend. While the request is processing, I want the button to display a loading indicator instead of the usual text. Once the request is complete, I need the form to disap ...

Taking advantage of Input decorator to access several properties in Angular 2

I am currently working on a component that is designed to receive two inputs through its selector. However, I would like to make it flexible enough to accept any number of inputs from various components. Initially, I tried using a single @Input() decorator ...

The file located at node_modules/@types/chrome/index.d.ts does not qualify as a module

I am currently working on a monorepo with a React TypeScript app. The issue I am facing is that when I try to use 'chrome' in any of my .ts files, VSCode displays an error message saying 'Cannot find name 'chrome'.' To resolv ...

The ngShow directive is being assessed prematurely

In my development project, I have an Angular component and controller set up in the following way: export class MyController{ static $inject = [MyService.serviceId]; public elements: Array<string>; public errorReceived : boolean; ...

Leveraging Json data in Angular components through parsing

I am currently developing an angular application where I need to retrieve and process data from JSON in two different steps. To start, I have a JSON structure that is alphabetically sorted as follows: { "1": "Andy", "2": &qu ...

Guidelines for generating a sorted indices array from a different array using TypeScript

I need help finding a way to create an ordered array of indexes from another array in TypeScript. Let me provide some examples: imagine a function that takes an array of any length and returns another array with the indexes of the elements in ascending or ...

Error with tsc rootDir due to Docker's installation of yarn in root directory

I am encountering a problem with my node project which serves a simple "hello world" server. Everything runs smoothly when I run it locally, but when I try to run it inside Docker, a /opt/yarn-v1.21.1 folder is created which leads to a rootDir error: erro ...

The index.ngfactory.ts file threw an unexpected token error, indicating that an appropriate loader may be necessary to handle this specific file

I've spent several hours trying to troubleshoot this persistent error, exhausting all online resources for solutions. The issue arises consistently with every module of Angular Material only during the build process using --env.prod. The webpack confi ...

What is the method for developing a Typescript-connected High-Order React Component with Redux?

I am looking to develop a React Higher-Order Component that can safeguard routes within my application from unauthorized users without an access token. I aim to use this HOC to wrap a Component like so in the parent component: <Route exact path ...