By leveraging core-js and Typescript with ES5 as the target, it is possible to utilize ES6 features

Currently, I am working on a TypeScript project that is compiled with the setting "target": "es5". In order to use core-js's Set, I have both core-js and @types/core-js installed in my project. The issue arises because the core-js d.ts file contains global declarations for ES6 features such as Set and Map. This causes the TypeScript compiler to allow me to use these features, even though they may not be supported in older browsers.

Unfortunately, I cannot exclude the core.d.ts file from the build process since it contains necessary interfaces that I need. Is there a way for the TypeScript compiler to prevent me from using ES6 features while still allowing me to use core-js and its corresponding type definitions?

Answer №1

When dealing with core-js as a polyfill, it's important to note that its declarations are intended to alter the global scope. To avoid potential conflicts, creating your own declaration for the set interface is recommended and relatively straightforward. Additionally, removing the @types/core-js package is advised.

An example of a declaration you could utilize is:

declare module "core-js/library/fn/set" {
  class Set { ... }
  export = Set;
}

It's worth mentioning that this serves as an ambient external module declaration with a name that corresponds to the import path of the actual JavaScript file as determined by your loader or node's require function.

Ambient external module declarations should generally be minimized to prevent cluttering the global namespace, although in certain cases, like this one, they may be necessary.

If you want to limit their usage, consider leveraging the paths configuration in your tsconfig.json file.

path-to-non-ambient-declaration.ts

class Set { ... }
export = Set;

tsconfig.json

{
  "compilerOptions": {
     "baseUrl": "",
     "paths": {
       "core-js/library/fn/set": [
         "path-to-non-ambient-declaration"
        ]
      }
    }
  }
}

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 bring in local modules within the browser environment using Playwright?

Let me illustrate what I am attempting to achieve: ../src/Foo/Bar.ts represents a local TypeScript file This particular file contains code that is designed to function within a browser environment (it utilizes WebSockets), and therefore needs to be execu ...

Upgrading to Angular 18 Leads to Issue with Spread Operator: 'TypeError: res is not iterable' Error

Following the migration of my Angular project from version 9 to version 18, a new error has surfaced: ERROR TypeError: res is not iterable onEscalate details.component.ts:735 RxJS 5 next _next next next error ...

Typescript encounters difficulties locating modules

I am encountering issues with my server's .ts files, as they are indicating that the modules and typings cannot be found even though I have already installed them and verified within the node_modules directory. Here is the structure of my project: vi ...

Is there a specific type required for the Vue `install` function? Is it necessary to have the `directive` property on the `Vue`

I've been working on implementing a Vue directive in typescript, but I'm struggling to determine the correct types to use for the Vue install function. Using install(Vue: any): void feels a bit strange to me. I attempted importing Vue and using ...

What is the reason behind Typescript flagging a potential undefined value when checking for array length using a greater than comparison but not with an

Consider the following excerpt from a React component: const AccountInformation = (props: { readonly accountData: AccountData | undefined | null }) => { const hasMultipleAccounts: boolean = props.accountData?.customerAccounts?.length === 1 ? false : t ...

Utilizing functional components and formatter functionality in React with react-jsx-highcharts

Exploring the capabilities of react-jsx-highcharts through a polar chart. Software Versions: React: 17.0.1 react-jsx-highcharts: 4.2.0 typescript: 4.0.3 I opt for functional components in my code, hence no usage of "class" or "this." The snippet f ...

Checking nested arrays recursively in Typescript

I'm facing difficulty in traversing through a nested array which may contain arrays of itself, representing a dynamic menu structure. Below is how the objects are structured: This is the Interface IMenuNode: Interface IMenuNode: export interface IM ...

Creating a mongoDB query that matches elements in an array of subdocuments with elements in a Typescript Array

In my database, I have stored various Events using mongoDB. Each event comes with multiple fields, including an array of genres, which consists of subdocuments like {genre and subGenre}. For instance, an event could be classified as {genre: "music", subGe ...

Tips on preventing repeated data fetching logic in Next.js App Routes

I'm currently developing a project with Next.js 13's latest App Routes feature and I'm trying to figure out how to prevent repeating data fetching logic in my metadata generation function and the actual page component. /[slug]/page.tsx expo ...

What prevents TypeScript from allowing an async function to return a combination of type T or Promise<T>?

During the development of my API in typescript, I encountered a situation where some controller actions can be synchronous while others cannot. To address this issue, I decided to specify a response type as follows: type ActionResult =IHttpActionResult | ...

How do I disable split panel on Ionic 2 login page exclusively?

I have successfully implemented the split-pane feature in my app.html file. However, I am facing an issue where the split pane is being applied to every page such as login and SignUp. Can someone please guide me on how to restrict the split pane function ...

The issue with the Angular 5 HttpClient GET-Request not closing persists

Currently, I am utilizing an Http-GET request to fetch JSON data from my backend service. Service: public storedCategories: BehaviorSubject<Category[]> = new BehaviorSubject(null); constructor() { const subscription = this.http.get&l ...

Import a JSON file into TypeScript declaration files (*.d.ts)

I am currently working on a declaration file where I need to establish a global type that is specifically tied to a predetermined list of string phrases. These string phrases are part of property keys within an object located in a JSON file. I have a coup ...

Encountering a problem with the syntax '[checked]= true' in Angular2

I am currently working on a system for managing orders within restaurants using an angular2 application. The code I have is as follows: <md-radio-group> <span *ngFor="let extIng of item.extra_ingredients;"> <md-radio-button *ngIf= ...

NodeJS Jest test failing due to a global variable being set for a different test already

I am currently working on a project in TypeScript using Node.js and Jest. I have a function that may or may not modify a global variable, which is a TypeScript Map. After one test modifies the global variable, it retains that value for subsequent tests. I ...

The error message "Property 'name' is not found in type 'RepositoryResponse[]'" is being displayed by Typescript

I am encountering an issue while attempting to retrieve data from the GitHub API. The error message indicates that values from the API are not present in the interface. API URL: interface Repository { name: string; avatar_url: string; ...

Create a new project using Firebase Functions along with a Node.js backend and a React.js frontend

In the process of developing my application, I have chosen to utilize node.js, express.js, and Firebase with firebase functions, all coded in TypeScript. For the client side framework, I am interested in incorporating react.js. Currently, I have set up nod ...

The function of type 'PromiseConstructor' is not executable. Should 'new' be added? React TypeScript

.then causing issues in TypeScript. interface Props { type: string; user: object; setUserAuth: Promise<any>; } const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => { e.preventDefault(); if (type === "signup" ...

Dealing with request-specific or session-specific data in LoopBack 4

I am currently facing a challenge within our LoopBack4 application. We have implemented controllers and are using JWT for Authorization. In the token's payload, we include a list of rights granted to the requesting user. Additionally, we have added an ...

How can you include a multi-layered array within another multi-layered array using TypeScript?

If we want to extend a two-dimensional array without creating a new one, the following approach can be taken: let array:number[][] = [ [5, 6], ]; We also have two other two-dimensional arrays named a1 and a2: let a1:number[][] = [[1, 2], [3, 4]]; let ...