How can use my own custom .d.ts files in an Angular 15 projects?

588 Views Asked by At

In an Angular 15 project I'm using bootstrap-italia which is a package that depends on "standard" Bootstrap and add some custom components and types. Contrary to what is indicated, the package does not contain built-in TypeScript declarations so I tried to create some.d.ts files by myself in a typings/bootstrap-italia folder in project root folder with a index.d.ts file and a plugins folder with a .d.ts for each component type I want but I cannot use them in the project as the compilation ends with the error Error: Module not found: Error : Can't resolve '../../../../../typings/bootstrap-italia' in 'C:\Users\ivanc\Dev\angular\CitizenPortal\Frontend\src\lib\components\various\ notification', how can I fix it?

typings/bootstrap-italia/index.d.ts:

import Notification from './plugins/notification';

export { Notification };

typings/bootstrap-italia/plugins/base-component.d.ts:

export type GetInstanceFactory<T> = (element: string | Element) => T | null;
export type GetOrCreateInstanceFactory<
  T,
  C extends ComponentOptions = ComponentOptions
> = (element: string | Element, config?: C) => T;
export type ComponentOptions = Record<string, any>;

export default class BaseComponent {
  static readonly VERSION: string;

  static readonly DATA_KEY: string;

  static readonly EVENT_KEY: string;

  constructor(element: string | Element);

  dispose(): void;
}

typings/bootstrap-italia/plugins/notification.d.ts:

import BaseComponent, { GetOrCreateInstanceFactory } from './base-component';

declare class Notification extends BaseComponent {
  static getOrCreateInstance: GetOrCreateInstanceFactory<
    Notification,
    Partial<Notification.Options>
  >;

  static Default: Notification.Options;

  constructor(
    element: string | Element,
    options?: Partial<Notification.Options>
  );

  toggle(relatedTarget?: HTMLElement): void;

  show(timeout?: number, relatedTarget?: HTMLElement): void;

  hide(): void;
}

declare namespace Notification {
  enum Events {
    show = 'show.bs.modal',
    hidden = 'hidden.bs.modal',
  }

  interface Options {
    timeout: number;
  }

  interface Event extends CustomEvent {
    target: HTMLElement;
    relatedTarget?: HTMLElement;
  }
}

export default Notification;

Then, in Angular components .ts file:

import { Notification } from '../../../../../typings/bootstrap-italia';
1

There are 1 best solutions below

0
On

I solved this issue by simply remove the ".d" in the file extension.

".d" extension is meant to say to Typescript that it's a decorational file, what you don't need to import. But, for some reason, it's not working. Removing the ".d" will handle this file as normal, so it'll work. Also, this issue persist only in some cases, like when I try to use an enum type in component-level variable.