What are the constants that TypeScript compiles at runtime?

I'm in the process of developing a TypeScript library that needs to support both Node and Browser environments. Currently, I have been compiling my code twice using tsc with different targets for each environment, and it seems to be functioning correctly.

However, a specific portion of my code is dependent on the target environment. I am looking for a way to handle this, such as:

if(BUILD_TARGET === 'node') {
    // execute certain code
} else {
    // execute alternative code
}

Is there a method for injecting these constants at compile-time so that they can possibly be optimized by tsc itself or a tool like UglifyJS?

Answer №1

Typescript offers `const enums` as a close alternative to compile-time constants, as noted in the documentation, stating that they are completely removed during compilation unlike regular enums.

However, there are drawbacks to using const enums, such as their incompatibility with the `isolatedModules = true` mode commonly used by bundlers.

Another limitation is that Typescript does not perform dead code elimination, requiring the use of external tools to remove branches like `if (0 === 1)` post-compilation.

To accommodate different enum definitions for the same type, separate `tsconfig.json` files must be utilized, each referencing a specific definition file.

tsconfig.browser.json

{
  "files": [
    "t.ts",
    "target-enum-browser.d.ts"
  ]
}

target-enum-browser.d.ts

declare module 'target-enum' {
    export const enum Target { Node, Browser, Current = Browser }
}

tsconfig.node.json

{
  "files": [
    "t.ts",
    "target-enum-node.d.ts"
  ]
}

target-enum-node.d.ts

declare module 'target-enum' {
    export const enum Target { Node, Browser, Current = Node }
}

t.ts

import {Target} from 'target-enum';

if (Target.Current === Target.Browser) {
    console.log('browser');

} else if (Target.Current === Target.Node) {
    console.log('node');
    
} else {
    console.log('?');
}

Compiled using

tsc --project tsconfig.browser.json

"use strict";
exports.__esModule = true;
if (1 /* Current */ === 1 /* Browser */) {
    console.log('browser');
}
else if (1 /* Current */ === 0 /* Node */) {
    console.log('node');
}
else {
    console.log('?');
}

Compiled using tsc --project tsconfig.node.json

"use strict";
exports.__esModule = true;
if (0 /* Current */ === 1 /* Browser */) {
    console.log('browser');
}
else if (0 /* Current */ === 0 /* Node */) {
    console.log('node');
}
else {
    console.log('?');
}

Answer №2

Visit this GitHub repository for more information

Currently focused on developing a compile time transformer

const numbers = [ 1, 2, 3, 4, 5, 6, 7, 8 ];
const result = comptime(() => {
    return numbers.reduce((total, x) => sum(total, x), 0);
});

transformed to:

const result = (() => { return (36); })();

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

What is the best way to create a linear flow when chaining promises?

I am facing an issue with my flow, where I am utilizing promises to handle the process. Here is the scenario: The User clicks a button to retrieve their current position using Ionic geolocation, which returns the latitude and longitude. Next, I aim to dec ...

Creating a TypeScript class that includes all the attributes of a pre-existing object type

One technique I frequently use in TypeScript involves transforming a plain JSON object definition into a class during runtime. Here's an example: export type LessonDef = { id: string title: string slug: string shortdesc: string explanation: ...

Breaking down large reducer into smaller reducers

I am currently working on a feature reducer (slice reducer) called animals. My goal is to separate these reducers into categories such as mammals, birds, fishes, and more. Initially, I thought this would be a smooth process using the ActionReducerMap. How ...

When working with Visual Studio and a shared TypeScript library, you may encounter the error message TS6059 stating that the file is not under the 'rootDir'. The 'rootDir' is expected to contain all source files

In our current setup with Visual Studio 2017, we are working on two separate web projects that need to share some React components built with TypeScript. In addition, there are common JavaScript and CSS files that need to be shared. To achieve this, we hav ...

In TypeScript, use a key index signature for any properties that are not explicitly defined

In various instances, I have encountered scenarios where it would have been beneficial to implement the following (in a highly abstracted manner): export interface FilterItem { [key: string]: string | undefined; stringArray?: string[]; } However, thi ...

Tips on preventing the need for null or undefined checks in JS/Typescript singletons that have an initialization function

Is there a way to streamline the process of handling props in an Object literal that is dynamically initialized only once? I'm looking for a pattern that would eliminate the need for repetitive null/undefined checks and throw errors when certain metho ...

Conditional type/interface attribute typing

Below are the interfaces I am working with: interface Movie { id: number; title: string; } interface Show { title: string; ids: { trakt: number; imdb: string; tmdb?: number; }; } interface Props { data: Movie | Show; inCountdown ...

Troubleshooting typescript error in styled-components related to Material-UI component

When using typescript and trying to style Material UI components with styled-components, encountering a type error with StyledComponent displaying Type '{ children: string; }' is missing the following properties import React, { PureComponent } f ...

Issues persist with @typescript-eslint/no-unused-vars not functioning as expected

.eslintrc.json: { "root": true, "ignorePatterns": ["projects/**/*"], "overrides": [ { "files": ["*.ts"], "extends": [ "eslint:recommended", ...

The react-bootstrap module does not have any members available for export

I'm looking to incorporate the npm module react-bootstrap from this link into my Layout component, following the ASP.NET Core 2.1 template client project structure. The challenge I'm facing is that the template uses a .js file extension, but I pr ...

Develop an Angular 6 application that utilizes an observable to monitor changes in a variable

I am working with Angular 6 and I need to monitor a variable for any changes and then stop or unsubscribe when the variable has a value. My initial thought was to use an Observable: myValue; // The variable that needs to be monitored myObservable = Obse ...

Does a typescript definition file exist for Apple MapKit JS?

Before embarking on creating one, I'm curious if anyone has come across a typescript definition file (.d.ts) for Apple MapKit JS? ...

Unable to run unit tests on project using my custom React library

If any of you have encountered this issue or know how to solve it, please help me. I created an NPM package that can be found at https://www.npmjs.com/package/@applaudo/react-clapp-ui It installs and runs smoothly in other projects using create react app; ...

Encountered an error with API request while utilizing Cashfree in a React Native environment

I'm currently integrating cashfree into my react native app for processing payments. Here is a snippet of the code I'm using: import { CFPaymentGatewayService, CFErrorResponse, } from 'react-native-cashfree-pg-sdk'; import { CFDr ...

Having trouble with the Angular Language Service extension in VS Code for Angular-16?

Upon transitioning to Angular 16, I encountered errors while attempting to edit the components HTML due to the malfunctioning of the Angular Language Service extension. [Info - 09:41:11] Angular language server process ID: 18032 [Info - 09:41:11] Using t ...

Can the inclusion of a type guard function impact the overall performance of the application?

const typeGuard = (param: any): param is SomeType => { return ( !!param && typeof param === "object" && param.someProperty1 !== null && param.someProperty2 === null ) } If a type guard function similar to the code above is exe ...

Encountering difficulties setting a value to a key within an Object in Angular/Typescript

I'm currently working with Angular, and I've encountered an issue while trying to assign a value to a key within my model. Here's a snippet of my code: export class aa{ types: bb[]; } export interface bb{ name: string; age: str ...

Unable to retrieve template generated using the innerHTML directive in Angular 4

I am in need of accessing the elements of a dynamically created component's DOM through the innerHTML directive in Angular. Below is my main component: import {Component} from '@angular/core'; @Component({ selector: 'app-root', ...

Establishing the correct data type to be returned from a fetch function in order to align with a specific custom type

My app has two interfaces defined: export interface Job { job_title: string, employer: string, responsibilities: string[] achievements: string[], start_date: string, end_date: string } export interface CreatedJob extends Job { ...

Creating a HandleCredentialResponse function in Angular version 14 for implementing the "Sign in with Google" feature using Typescript

In the process of building a very simple angular version 14 application, I am working on displaying a 'Sign in with Google button' and incorporating the login functionality. For information about the new method of Sign in With Google, you can re ...