Issue with Angular 7: Difficulty integrating a personalized TypeScript declaration file

Recently, I created a custom TypeScript definition file called brat.d.ts

export declare class head {
   ready(callback: () => any);
}

export declare class Util {
   static embed(divId: string, collData: any, docData: any, webFontsURLs: Array<string>);
}

In my Angular 7 components, I have been importing the above definition file like this:

import {head, Util} from "../../brat/brat";

However, when I attempt to run 'ng serve', I encounter the following error message:

'ERROR in ./src/app/folder-mgmt/list-documents/list-documents.component.ts Module not found: Error: Can't resolve '../../brat/brat' in '\src\app\folder-mgmt\list-documents'`

I'm seeking advice or suggestions on what could be the issue. Any insights would be greatly appreciated.

Answer №1

To make declarations accessible throughout your project, simply add them to a .d.ts file. However, you must make adjustments to the tsconfig.json first by including the following:

"files": [
  "extra-declarations.d.ts"
]

Next, create a ./extra-declarations.d.ts file (relative to your TypeScript project root) and define your typings there without using export.

declare class customFunction {
   runTask(callback: () => void);
}

declare class Helper {
   static loadScript(elementId: string, data: any, fontsURLs: Array<string>);
}

This will grant global access to your declarations.

If you prefer not to expose these declarations globally, declare them within a module if you are providing typings for a missing module.

declare 'custom-module' {
  // ...
}

By doing so, TypeScript will properly recognize them when importing with

import { ... } from 'custom-module'
.

Answer №2

To tackle this issue, I took the following steps:

I edited my custom typescript definition file (brat.d.ts) to remove the export keyword and updated it as follows:

declare class head {
   static ready(callback: () => any);
}
declare class Util {
   static embed(divId: string, collData: any, docData: any, webFontsURLs: Array<string>);
}

When working on an Angular project generated using Angular CLI, there will be a tsconfig.json file in the project's root directory.

I included the path to the folder containing the custom definition file in the "typeRoots" property under "compilerOptions" within tsconfig.json.

https://i.sstatic.net/nowyU.png

In the Angular component, I removed the import statements that were used to import the custom typescript definition file ("brat.d.ts" in this case).

Answer №3

Encountered a similar issue recently and after conducting some thorough research and referring to various resources, I found the solution. In your case, it's essential to ensure correct import statements. For example, in order to import {head, Util} from "../../brat/brat"; make sure to use import {head, Util} from "../../brat/brat.d";
When importing modules, remember not to include the file extension while your module is named brat.d.ts.

In my scenario, there was a conflict with a file/module named item.ts which included the exported class 'Item'.

export class Item {
  public reference: string;
  public name: string;
   constructor( name: string, reference: string) {
     this.reference = reference;
     this.name = name;
   }
   get getReference(): string {
     return this.reference;
   }
   get getName(): string {
     return this.name;
   }
   set setName(newName: string) {
      this.name = newName;
   }
 }

Upon importing with

import { Item } from './models/item';
in the component where the class is used, and saving (Ctrl+s), an error message appeared stating
ERROR in src/app/app.component.ts(2,20): error TS2306: File 'D:/PROJET/Personal Resoruces/Angular2/DuckFowl/src/app/Models/item.ts' is not a module.
. By changing the filename to item.models.ts without altering the class itself, the issue was resolved. Keeping the module name distinct from the exported element can be beneficial, but the choice of names is flexible.

Remember to save both the file containing the exported element and the Component using Ctrl + s to refresh Angular CLI.

This approach successfully resolved the problem for me.

Screen shot of project component and model

My Configuration Details:

Angular CLI: 8.3.6
Node: 10.16.0
OS: win32 x64
Angular: 8.2.8
... animations, common, compiler, compiler-cli, core, forms
... language-service, platform-browser, platform-browser-dynamic
... router

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.803.6
@angular-devkit/build-angular     0.803.6
@angular-devkit/build-optimizer   0.803.6
@angular-devkit/build-webpack     0.803.6
@angular-devkit/core              8.3.6
@angular-devkit/schematics        8.3.6
@angular/cli                      8.3.6
@ngtools/webpack                  8.3.6
@schematics/angular               8.3.6
@schematics/update                0.803.6
rxjs                              6.4.0
typescript                        3.5.3
webpack                           4.39.2

Spread Love & Lead On!

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

Can you please explain to me the purpose of the ncu -u command?

Struggling to update my Angular project in Visual Studio to a specific version of Angular. Instead of following the tutorial that provided me with the latest Angular version, I wanted to install version 6 specifically. So, I ran npm install -g @angular/ [ ...

What is the best way to handle .jsx files in my library bundling process with Rollup?

Currently, I am in the process of developing a component library using storybook and rollup. Here is the configuration file rollup.config.mjs /* eslint-disable import/no-extraneous-dependencies */ import peerDepsExternal from 'rollup-plugin-peer-deps- ...

Is there a way to transfer data from a custom hook to a component seamlessly?

I am facing an issue with a custom hook that passes parameter data along with fetched data to the Settings component. Inside Settings, I have a hook called setData11 in useEffect and I am trying to set the data passed from useTable but encountering an er ...

The type 'string' cannot be assigned to the specified type

I'm attempting to establish a constant that can only contain two specific values as displayed in the code snippet. The variable state.lang is already ensured to be type-safe with a value of either en or ar. const keyname: 'owner_name_en&apos ...

Creating a unique optional string array interface in TypeScript

I am looking to create an interface that includes optional string values. Here is what I have in mind: interface IEntity { values: ['RemainingUnits', 'ActualUnits', 'PlannedUnits'] } However, when implementing this inter ...

Is it possible to determine when a component has completed its rendering process in Angular?

I am currently working on an Angular application where I have a page component that contains several subcomponents. Each subcomponent is set up to fetch data from an API in the ngOnInit method, causing a layout shift issue as they load at different speeds ...

Display the autocomplete dropdown in Angular 2+ only once the user has typed at least one letter

Looking to create a customized autocomplete feature using Angular 2+ and angular material design, where the options are only displayed after at least one letter has been typed. The default behavior of the autocomplete is to toggle on focus even when the i ...

Ensuring there are no null values in TypeScript

I am encountering an issue with the following TypeScript code: console.log ('collection[0] -> ' + collection[0] ); console.log ('collection[0] !== null -> ' + collection[0] !== null); However, the output on the console is unexp ...

The parameter type must be a string, but the argument can be a string, an array of strings, a ParsedQs object, or an array of ParsedQs objects

Still learning when it comes to handling errors. I encountered a (Type 'undefined' is not assignable to type 'string') error in my code Update: I added the entire page of code for better understanding of the issue. type AuthClient = C ...

How can we toggle a function to expand or collapse fields generated in an ngFor loop?

One of my challenges involves managing a div that is repeated using *ngFor in Angular. This results in multiple divs on the page, each containing collapsible fields that can toggle. Essentially, I have nested collapsible fields within other collapsible fie ...

Angular 2: Unable to locate collection

Just starting out with Angular2 and attempting to create a Todo app. Here is the file structure I am working with: https://i.sstatic.net/ppYWd.png Review of the todo.service.ts code (located in the shared folder) import { Injectable } from '@angul ...

Retrieve the previous value of the selection change with the Mat Select function

In my current project, I have a form with a mat-select dropdown. Whenever the user makes a selection, a dialog pops up to confirm the choice. However, I am facing an issue: The selectionChange() event is triggered when the value changes and provides the n ...

Removing invalid characters in a *ngFor loop eliminates any elements that do not meet the criteria

I am facing an issue with my *ngFor loop that is supposed to display a list of titles. fetchData = [{"title":"woman%20.gif"},{"title":"aman",},{"title":"jessica",},{"title":"rosh&quo ...

FIXED-IONIC 3: The 'questions' property is missing from the 'Object' type

Encountering an issue with a single line of code and exhausted all resources in attempts to resolve it. Seeking assistance for my simple quiz, disregarding the current data presentation. The trouble arises within my data.ts file, specifically at one parti ...

Do Typescript interfaces check method parameters for validation?

interface optionsParameter { url: string; } function DEC(options: optionsParameter){ } DEC(2) //typescript check compilation error let obj:any = { name: "Hello" } obj.DEC = function(options: optionsParameter){} obj.DEC(1); // no compilation ...

choose to display on mobile devices as a dropdown menu rather than a modal window

On mobile devices, my select elements are currently displayed as modals with options. However, I need to change this appearance to resemble the dropdown list view observed on desktop devices. Your assistance is greatly appreciated. ...

Use 'data-toggle='button'' in Angular component only once the condition is validated

Looking to verify a certain condition upon clicking, and if it evaluates to true, toggle the element that was clicked <div class="btn-group btn-group-toggle" data-toggle="buttons"> <label class="btn btn-secondary active" (click)='example ...

What is the reason behind RematchDispatch returning a `never` type when a reducer and an effect share the same name?

Recently, I made the switch from TypeScript 4.1.2 to 4.3.2 with Rematch integration. Here are the Rematch packages in use: "@rematch/core": "2.0.1" "@rematch/select": "3.0.1" After the upgrade, a TypeScript error p ...

Guide to making a sidebar for your chrome extension using Angular, no need for an iframe

I am currently developing a chrome extension using Angular, and it functions similarly to the MaxAI chrome extension. When the user clicks on the widget, it triggers the opening of a sidebar. Although I have followed a few tutorials to create a sidebar, t ...

Troubleshooting Problems with Data Binding in Angular 6

After switching from Angular JS 1.6 to Angular 6, I encountered a problem while working on an app in Angular 6. The [(ngModel)]="number1" directive for 2-way data binding caused my component to stop rendering. When I switched to (ngModel), the component ...