Using const enums across multiple files with react-scripts-ts

Within our project, we have two distinct subprojects (backend and frontend) that are compiled independently. The frontend utilizes react-scripts-ts, so it is crucial to avoid cross-imports between the two subprojects to maintain the integrity of the transpiled code structure. The project's layout is as follows:

/
|-client
| |-src
|   |-index.tsx
|   |-common.d.ts
|-src
  |-custom.d.ts
  |-app.ts

Here is a simplified overview of the current project structure. On the client side:

common.d.ts:

type UnionType = 'string1' | 'string2';

index.tsx:

import * as React from 'react';
import * as ReactDOM from 'react-dom';

const enum Type {
    Type1 = 'Type1',
    Type2 = 'Type2'
}

interface Props {
    param1: Type;
    param2: UnionType;
}

class App extends React.Component<Props> {
    render() {
        switch (this.props.param1) {
            case Type.Type1:
                return <div>{'Type 1 + ' + this.props.param2}</div>;
            case Type.Type2:
                return <div>{'Type 2 + ' + this.props.param2}</div>;
        }
    }
}

ReactDOM.render(
<App
    param1={Math.random() > 0.5 ? Type.Type1 : Type.Type2}
    param2="string1"
/>, document.getElementById('root'));

On the server side:

custom.d.ts:

/// <reference path="../client/src/common.d.ts" />

app.ts:

const enum Type {
    Type1 = 'Type1',
    Type2 = 'Type2'
}

const type: Type = Type.Type1;
const item: UnionType = "string1";
console.log(`Result is "${type}" + "${item}"`);

There is a desire to eliminate code duplication by moving the const enum Type to common.d.ts. However, simply declaring it in the common file and removing it from both index.tsx and app.ts does not yield the desired outcome:

declare const enum Type {
    Type1 = 'Type1',
    Type2 = 'Type2'
}

Although the backend properly inlines the declaration, the frontend compilation using react-scripts-ts retains all references to Type.Type1 in their original form, ultimately causing runtime errors due to the absence of the corresponding object.

You can find a reproducible example of this issue in the repository here.

Is it feasible to reference the same const enum from various locations without importing it at all?

Answer №1

The issue arises specifically with the combination of react-scripts-ts and ts-loader in transpileOnly mode. This setup translates each source file independently, disregarding errors, which can lead to unresolved const enums and other TypeScript features not functioning as expected when code dependencies are involved. In essence, certain toolchain functionalities are incompatible with these features.

For more information on this problem, check out this ts-loader issue.

Answer №2

The code encounters a runtime failure because the object it is looking for does not exist and should not be present.

Avoid using a `const enum` across different projects to prevent potential runtime problems from occurring consistently.

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

Utilizing TypeScript Generics to Dynamically Set Tag Names in React

I am working on a straightforward polymorphic React component that is designed to render only tag names (such as span) and not custom React components (like MyComponent). I believe this can be achieved using JSX.IntrinsicElements. Here is the code snippet ...

The SonarQube code coverage differs from that of Jest coverage

I'm struggling to grasp why SonarQube and Jest coverage results differ so significantly. SonarQube coverage resultshttps://i.sstatic.net/dodGi.png Jest coverage https://i.sstatic.net/uYKmt.png https://i.sstatic.net/rakzw.png https://i.sstatic.net/ ...

Tips for setting values to the child component property in Angular 4

When I was using ngif, I encountered an issue with getting the element reference of the child component. After extensive searching, I discovered that in order to access the element, I needed to use view children instead of view child. While I am able to ge ...

What steps can I take to prevent encountering a Typescript Error (TS2345) within the StatePropertyAccessor of the Microsoft Bot Framework while setting a property?

During the process of constructing a bot in Typescript, I encountered TS2345 error with Typescript version 3.7.2. This error is causing issues when attempting to create properties dynamically, even if they are undefined, or referencing them in the statePro ...

Is there a way to organize items in an array alphabetically according to a predetermined key value?

I have an array of objects containing countries with various values for each country. My goal is to list them alphabetically. // globalBrands { [ { id: 1, title: 'Argentina', content: [{url: 'w ...

Issue with type narrowing and `Extract` helper unexpectedly causing type error in a generic type interaction

I can't seem to figure out the issue at hand. There is a straightforward tagged union in my code: type MyUnion = | { tag: "Foo"; field: string; } | { tag: "Bar"; } | null; Now, there's this generic function tha ...

Top method for dynamically loading a specific component by using its selector as a variable

I'm currently in the process of developing a straightforward game using Angular. The game is structured to consist of multiple rounds, each with unique characteristics that are distinguished by the variable roundType. For instance, round types can in ...

Steps for incorporating a type declaration for an array of objects in a React application with TypeScript

How can I specify the type for an array of objects in React using TypeScript? Here is the code snippet: const SomeComponent = (item: string, children: any) => { //some logic } In this code, you can see that I am currently using 'any' as ...

Adding ngrx action class to reducer registration

Looking to transition my ngrx actions from createAction to a class-based approach, but encountering an error in the declaration of the action within the associated reducer: export enum ActionTypes { LOAD_PRODUCTS_FROM_API = '[Products] Load Products ...

What is the reason for calling Proxy on nested elements?

Trying to organize Cypress methods into a helper object using getters. The idea is to use it like this: todoApp.todoPage.todoApp.main.rows.row .first().should('have.text', 'Pay electric bill'); todoApp.todoPage.todoApp.main.rows.ro ...

Attempting to assign the object retrieved from the interface as the new value for window.location.href

I encountered an issue where the error message Type MyInterface' is not assignable to type 'string' popped up. Although I comprehend the problem, finding a suitable solution has proven to be challenging. MyInterface solely returns one item, ...

Guide to leveraging tanstack table v8 for sorting data within a specific date range

Received data from API: const abc = [ { date: '2023-12-8', value: 'mop' },{ date: '2023-10-8', value: 'qrs' } ] How can we create a date range using two input fields when the dates are in string forma ...

Combining tuples with their corresponding data types

Trying to define a new type: type Union = [1, "one"] | [1, "first"] | [2, "two"] type GetTuple<T, U> = Extract<T, [U, ...unknown[]]>; type ObjectFromUnion<T extends Union[0] = Union[0]> = { number: T, word: ?? } Looking to utiliz ...

What is the process for linking my component to my socket.io server?

I am facing a challenge in setting up a socket.io server to facilitate communication between two components: a command interface for sending data, and an overlay component for receiving it. Below is the code snippet: interface.component.html : <input ...

Creating a personalized state object containing unresolved promises in React Native utilizing axios inside a custom React Hook

I'm currently in the process of creating a custom state within a custom Hook for React Native (non-Expo environment). The state I am working on looks like this: interface ResponseState { api1: { error: boolean; errorMsg?: string; ...

Although there may be some issues with tslint, the functionality is operating smoothly

I am in the process of learning tslint and typescript. Currently, I am facing an issue that I need help with. Could you provide guidance on how to resolve it? Despite conducting some research, I have been unable to find a solution. The relevant code snippe ...

Exiting a void method in JavaScript/Typescript using the return or break statement

I find myself dealing with a complex method in Typescript that contains multiple if else if else constructs. It's a void method, and I'm wondering how I can exit the method based on a specific if condition without having to execute the remaining ...

Solving automatically generated TypeScript MongoDB types for GraphQL results

Utilizing the typescript-mongodb plugin along with graphql-codegen to automatically generate Typescript types enables easy data retrieval from MongoDB and GraphQL output via Node. The initial input schema in GraphQL format appears as follows: type User @ ...

Utilizing Typescript's type inference within a universal "promisify" function

Unique Context Not long ago, I found myself delving into the world of "promisification" while working on a third-party library. This library was packed with NodeJS async functions that followed the callback pattern. These functions had signatures similar ...

Generating a random number to be input into the angular 2 form group index can be done by following these

One interesting feature of my form is the dynamic input field where users can easily add more fields by simply clicking on a button. These input fields are then linked to the template using ngFor, as shown below: *ngFor="let data of getTasks(myFormdata); ...