Adjust the properties within enums in TypeScript based on the current environment

I am looking to dynamically remove specific enum properties based on the environment.

For example, in the build environment, I require all the enums:

export enum ERROR_TYPE {
    InvalidComponent = 'invalid_component',
    ForOnPrimitiveOrNull = "for_on_primitive|null",
    InvalidEventHandler = "invalid_event_handler",
    InvalidFormatter = "invalid_formatter",
    PropDataTypeMismatch = "prop_data_type_mismatch",
    RendererNotFound = "createRenderer_not_found",
    MutatingProp = "mutating_prop",
    SetSameValue = "set_same_value"
}

However, for the production environment, I only need a subset of the enum properties:

export enum ERROR_TYPE {
    InvalidComponent = 'invalid_component',
    ForOnPrimitiveOrNull = "for_on_primitive|null",
    InvalidEventHandler = "invalid_event_handler",
    InvalidFormatter = "invalid_formatter",
}

Is there a way to achieve this? If not, what is the recommended approach or alternative solution?

I want to exclude these unnecessary codes from the bundle size as they are not used in the production environment.

Answer №1

After extensive deliberation, I have discovered the optimal approach -

To incorporate static typing, I am establishing an interface

export interface IErrorType {
    InvalidField: 'invalid_field';
    IncorrectFormatter: "incorrect_formatter";
    DataTypeMismatch: "data_type_mismatch";
    RendererNotLocated: "renderer_not_found";
    ForPrimitiveOrNullable: "for_primitive_or_null";
    MalformedEventHandler: "malformed_event_handler";
    AssigningIdenticalValue: "assigning_identical_value";
    AlteringProperty: "altering_property";
}

thus consolidating all errors within the interface IErrorType

subsequently, I transformed my enumerations into a constant with type IErrorType, while assigning the development environment's enums under certain conditions. This ensures that only production-related enums are included in the production bundle.

export const ERROR_TYPE = {
    InvalidField: 'invalid_field',
    IncorrectFormatter: "incorrect_formatter",
    DataTypeMismatch: "data_type_mismatch",
} as any as IErrorType;

if (process.env.NODE_ENV !== 'production') {
    Object.assign(ERROR_TYPE, {
        ForPrimitiveOrNullable: "for_primitive_or_null",
        MalformedEventHandler: "malformed_event_handler",
        AssigningIdenticalValue: "assigning_identical_value",
        AlteringProperty: "altering_property",
        RendererNotLocated: "renderer_not_found",
    });
}

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

Is there a way to alter the value of an Observable using Knockout and Typescript within its subscription?

Question: What is the best way to update the value of an Observable from within its subscription using Knockout and Typescript? I am currently in the process of refactoring some old Knockout code to use Typescript. While going through the code, I came acr ...

Understanding Restangular with Typescript can be challenging, especially when dealing with a 'restangularized' response object

In my project, I am working with Angular 1.5.x using TypeScript in combination with restangular to access a remote API. Here is an overview of the scenario: The API endpoint I am connecting to is http://localhost:53384/api/timezones. Making a GET request ...

Sending data to the server using AngularJS 1.x and Typescript

I am encountering an issue where the header values I'm trying to post to the server are not properly embedded in the request header, resulting in incorrect answers. I understand that there is a mistake in my approach, but I can't seem to pinpoint ...

Navigating through the typings directory in Visual Studio 2015

Is it necessary to include the typings folder as part of an asp.net application in Visual Studio 2015 when using typings? I would like to handle the typings folder similar to the bower_components folder - not checking it and not including it in my solutio ...

"Typescript: Unraveling the Depths of Nested

Having trouble looping through nested arrays in a function that returns a statement. selectInputFilter(enteredText, filter) { if (this.searchType === 3) { return (enteredText['actors'][0]['surname'].toLocaleLowerCase().ind ...

Ways to send a variable to ngIf

header.component.html <ng-container *ngFor="let headerMenu of headerMenus"> <li *ngIf="headerMenu.ngif"> <a (click)="onClick(headerMenu.menu)" [class]="headerMenu.menu"> <img [src]="headerMenu.src" [alt]="heade ...

Setting a class for an HTML element within an ngFor loop

<div class="weather-app-wrapper" *ngIf="weather !== undefined"> <div class="weather-wrapper" *ngFor="let forecast of weather.forecastDays"> <div class="weather-card"> <div class="forecast-icon" [ngClass]="{{fore ...

When you sign up for the service, you might receive null values in return

I am currently in the process of subscribing to a service that needs access to the REST back-end using the specified object. export class Country { iso: String; iso3: String; name: String; niceName: String; numCode: number; phoneC ...

Creating anchor links with #id that function correctly in an Angular project can sometimes be challenging

My backend markdown compiler generates the HTML content, and I need Angular to retrieve data from the server, dynamically render the content, and display it. An example of the mock markdown content is: <h1 id="test1">Test 1<a href="#test1" title ...

Programmatically deselecting a radio button in code

How can I programmatically uncheck the radio button posted below using TypeScript? I attempted to set the value of averageHeight to false, but that did not result in the radio button being unchecked. Can you please provide guidance on how to achieve this? ...

Can a function's return type be set to match the return type of its callback function?

Check out the following function export const tryAsyncAwait = async (fn: () => any) => { try { const data = await fn(); return [data, null]; } catch (error) { return [null, error]; } }; If I use this function as an example... const ...

What are the benefits of using index signature `{[key: string]: any}` over the `object` type declaration?

As I delve into learning TypeScript, I frequently encounter the use of index signatures in function parameters. For example, export function template(resources: {[key: string]: any}) Given that the value type is any, what is the utility of this type? Is t ...

Directly mapping packages to Typescript source code in the package.json files of a monorepo

How can I properly configure the package.json file in an npm monorepo to ensure that locally referenced packages resolve directly to their .ts files for IDE and build tooling compatibility (such as vscode, tsx, ts-node, vite, jest, tsc, etc.)? I want to a ...

Trouble detecting type definitions in Typescript typeRoots

I'm incorporating TypeScript into my project. When I attempt to bring in a package using commonJS const { v4: uuidv4 } = require('uuid'); No errors occur during compilation. However, when I transform it into an ES6 module like this: import ...

Develop a series of sequential tests for the playwright to execute

Can someone assist me with my code? I am attempting to write a test in Playwright that navigates to the forgot password page, creates a new password, and then tries to log in using that new password. However, I am encountering an issue with retrieving the ...

The border of the Material UI Toggle Button is not appearing

There seems to be an issue with the left border not appearing in the toggle bar below that I created using MuiToggleButton. Any idea what could be causing this? Thank you in advance. view image here view image here Just a note: it works correctly in the ...

Error in Next.js when trying to use Firebase Cloud Messaging: ReferenceError - navigator is not defined in the Component.WindowMessagingFactory instanceFactory

Currently, I am in the process of setting up push notifications with Firebase in my next.js application. I have been following a guide from the documentation which you can find here: https://firebase.google.com/docs/cloud-messaging/js/receive?hl=es-419 Ho ...

Error: Emit was called before the Angular Webpack plugin was initialized while running npm start

An issue arises: Attempted emission before initialization of Angular Webpack plugin. Error: Failed to start Angular compilation - The Angular Compiler needs TypeScript version >=5.2.0 and <5.3.0, but it found 5.4.5 instead. ** The Angular Live Deve ...

Client Components can only receive plain objects and select built-in items from Server Components

My NextJs application has an "admin" page using Vercel Postgres. The issue I am facing is that when I fill in the inputs and click on the "Create user" button, a new user should be created. However, upon clicking the button, I encounter this error: Error ...

The context value is lagging behind and not updating promptly

context.tsx import { PropsWithChildren, createContext, useContext, useState } from "react"; import auth_svc from "../services/authServices"; import { Result, message } from "antd"; interface Result { _id: String | null; f ...