Issues with extensions during the Angular 9 Ivy compilation process

Good day!

After upgrading a v8 project to v9, I encountered some errors related to extensions in the compiler. These errors are not present in another project that I also recently upgraded.

The extensions, which are basic for constructors and prototypes, are set up correctly. They work without any issues in other projects, so it's puzzling why they are causing errors in this specific project.

To confirm the basic usage:

Add the following to typings.d.ts:

interface StringConstructor {
  isNullOrEmpty(str: string): boolean;
}  
interface String {
  padStartWithChar(char: string, totalSize: number): string;
}

Implementation:

export {};

String.isNullOrEmpty = function(str: string): boolean {
  // ...
};

String.prototype.padStartWithChar = function(this: string, char: string, totalSize: number): string {
  // ...
}

And import in main.ts:

// ...
import './extensions/string-extensions';
// ...

The paths are correct and the files are in the expected locations, yet build errors persist. The compilation fails with errors related to the extensions, causing the build to halt.

...

src/extensions/string-extensions.ts:9:8 - error TS2339: Property 'isNullOrEmpty' does not exist on type 'StringConstructor'.

9 String.isNullOrEmpty = function(str: string): boolean {

...

** Angular Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200/ **

Browsing results in a 'Cannot GET/' message, but saving files triggers a re-build that eventually completes successfully despite the error messages.

If anyone has insight on solving this issue, I would greatly appreciate the help. I have compared configurations between the two projects but have not been able to identify the cause of the errors.

Thank you.

Edit:

After reverting and attempting the upgrade again, I encountered errors with the extensions at the initial steps of the upgrade process. Skipping certain steps and attempting a direct upgrade to v9 also resulted in issues.

Update:

Following Richard's advice, most of the extension errors were resolved. However, errors related to Date extensions persist, particularly with the DateConstructor interface and the usage of moment.

Update edit:

Date extensions exhibit similar issues to other extensions, but the presence of import moment from 'moment' seems to complicate matters. Removing this import does not resolve the problem, indicating that Date extensions behave differently compared to String or Array extensions.

Answer №1

In order to fix the issue in my code file called extensions.ts, I had to delete the line export {}; and redefine the interface.

extensions.ts

interface String {
  format(...args: string[]): string;
  endsWith(searchString: string, position?: number): boolean;
}

if (!String.prototype.hasOwnProperty('format')) {
    String.prototype.format = function (...args: string[]): string {
        ...
    };
}

if (!String.prototype.hasOwnProperty('endsWith')) {
    String.prototype.endsWith = function (searchString, position) {
        ...
    };
}

Answer №2

After encountering a similar error in another project, I have finally pinpointed the issue!

I received build warnings advising me to

Add only entry points to the 'files' or 'include' properties in your tsconfig
.

Upon comparing the tsconfig.app.json file in the current project I'm updating with the previous one, along with the warnings mentioned above, the difference became apparent!

Here is the previous configuration:

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/app",
    "baseUrl": "./",
    "module": "es2015",
    "types": []
  },
  "exclude": [
    "test.ts",
    "**/*.spec.ts"
  ]
}

Here is the new configuration, addressing the warnings by adding main and polyfills files, and then fixing the extensions:

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/app",
    "types": ["node"]
  },
  "files": [
    "main.ts",
    "polyfills.ts"
  ],
  "include": [
    "**/*.d.ts",
    "extensions/*.ts"
  ],
  "exclude": [
    "test.ts",
    "**/*.spec.ts"
  ]
}

It appears including these files is essential!

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

Accessing Properties or Methods in Angular2 Components

My application consists of 3 main components: PageMenu, LoginSession, and LoginForm. The purpose is to establish a connection between the variables in LoginSession and PageMenu, allowing for the proper functionality of the LoginForm component. PageMenu: ...

Is there a way to associate a click event with an angular2 template interpolation?

Can a click event be bound to an interpolation? Whenever I try to run the code below, I encounter the following ERROR Error: Uncaught (in promise): Error: Template parse errors: Parser Error: Got interpolation ({{}}) where expression was expected at col ...

A mistake occurred during the afterAll function, resulting in a TypeError: Unable to access properties of an undefined entity (specifically, trying to read '

While creating my spec file and settings, I encountered an error in the console: 'An error was thrown in afterAll TypeError: Cannot read properties of undefined (reading 'toLowerCase')', What could be causing this error to appear? H ...

When onSubmit is triggered, FormData is accessible. But when trying to pass it to the server action, it sometimes ends up as null

I am currently utilizing NextJS version 14 along with Supabase. Within my codebase, I have a reusable component that I frequently utilize: import { useState } from 'react'; interface MyInputProps { label: string; name: string; value: stri ...

ReactJs Error: Unable to access property value because it is undefined (trying to read '0')

I am currently attempting to retrieve and display the key-value pairs in payload from my JSON data. If the key exists in the array countTargetOptions, I want to show it in a component. However, I am encountering an error message stating Uncaught TypeError ...

Inversify employs dependency injection similarly to how Angular utilizes TypeScript decorators

Today I made the switch from a js electron project to typescript and found myself wondering about the equivalent of angular's dependency injection. Since Angular Universal is still in its early stages and lacks documentation on using it with electron ...

Form with checkboxes in a Next.js and Typescript application

I am currently working on a project using Next.js and Typescript. I have implemented a form in this project, which is my first experience with Typescript and checkbox types. However, I am encountering difficulties in retrieving all checkbox values, adding ...

Unlock the power of Push Notifications with Ionic!

Currently, I am working on a project using Ionic for front-end development, Node.js + Express for the backend, and MongoDB as the database. My goal is to integrate push notifications into the app. I have come across information about utilizing Firebase f ...

nodemon failing to automatically refresh files in typescript projects

I am currently developing an app using NodeJs, express, typescript, and nodemon. However, I am encountering an issue where the page does not refresh when I make changes to the ts files. Is there a way for me to automatically compile the ts files to js an ...

How can I modify the ngx-datatable pager component to display text instead of icons and include a totalVisible property?

I am currently customizing the datatable-pager in ngx-dataTable and have been successful in adding footers and pagers. However, I am facing two issues that need resolution: How can I display text instead of icons for the prev/Next/First and Last buttons? ...

Changes made to the updated component fields are not reflecting on the user interface

I've encountered an issue where I can't seem to update a variable in a component that is being displayed on the UI. Even though the content of the variable changes correctly, the UI fails to reflect this change. Strangely enough, when checking th ...

Tips for postponing the listening observer experience?

One of my components is triggered by a conditional show: <app-list *ngIf="show"></app-list> At the same time, I emit an event in the same place where I activate this component: this.tabsEvens.emitMoveToVersions(version); this.router.navigate ...

Slow auto page refresh in local development for Angular2 on Windows can be quite frustrating

Recently diving into angular2 and following the heros tutorial from docs. Struggling with a sluggish development experience while working with angular2. It's taking approximately 5 seconds for angular2 to recognize changes in files, followed by anothe ...

Is it necessary to include a module in another module if it is not utilized in the template?

Is it necessary to import Module2 into Module1 if a component from Module2 is being used in Module1, but only in the typescript and not the template? For instance, as a @ContentChild(Component2) component2 like shown below (Note: both modules are secondary ...

Unveiling Angular library dependencies

Is there a way to conceal internal dependencies when developing an angular library? For example, during the development of my library, I added this dependency: yarn add moment-es6 However, I want to keep this as only an internal dependency and not impos ...

Is it possible for a Firestore query using .where() to conduct a search with no results?

Currently, I am in the process of creating a platform where users can upload past exams. Each document contains various fields such as teacher, year, and class, all stored in cloud Firestore. To filter the data by teacher, I am using the .where("Teacher" ...

retrieve the router information from a location other than the router-outlet

I have set up my layout as shown below. I would like to have my components (each being a separate route) displayed inside mat-card-content. The issue arises when I try to dynamically change mat-card-title, as it is not within the router-outlet and does not ...

Could it be that the Angular query is not returning any data? Or perhaps the issue lies with the dropdown selection not retrieving the data. It's possible that there may be a

I am facing an issue where I am not receiving the complete data from my form query. The query includes a search and mat select dropdown. I need both the selected values back in order to filter elements based on them. However, I am only getting the 'ti ...

The exit code 1 was triggered in the npm-lifecycleindex.js file at line 285,

0 silly lifecycle <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bac9ced5c8d194c9cadbfa8b948a948a">[email protected]</a>~build.prod: Args: [ '/d /s /c', 10 silly lifecycle 'gulp build.prod --color --en ...

Encountering an issue while running Angular 2 and Node.js server with the command 'npm

I encountered an issue while trying to run the project in production, After executing npm run build: prod, the compilation is error-free. However, when I run npm run server: prod, I encounter the following problem: C:\Users\Test\Project> ...