Guide on importing an interface from an external ngModule library

Just getting started with angular 4
I've put together an ngModule package called

mds.angular.bootstrap.datetimepicker
and here's the content of the package.json

{
  "name": "mds.angular.bootstrap.datetimepicker",
  "version": "0.9.8",
  "description": "Persian and gregorian DateTimePicker with angular 4",
  "license": "MIT",
  "main": "./mds-datetimePicker.module.js",
  "types": [
    "./mds-datetimePicker.module.d.ts",
    "./assests/date.interface.d.ts",
    "./assests/day.interface.d.ts",
    "./assests/rangeDate.interface.d.ts"
  ],
  "moduleResolution": "node",
  "author": {
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3f525b4c604c50594b7f465e575050115c5052">[email protected]</a>",
    "name": "Mohammad Dayyan",
    "url": "https://github.com/Mds92/mds-angular-bootstrap-datetime-picker"
  },
  "repository": {
    "type": "public",
    "url": "https://github.com/Mds92/mds-angular-bootstrap-datetime-picker"
  },
  "homepage": "https://github.com/Mds92/mds-angular-bootstrap-datetime-picker",
  "dependencies": {
    "@angular/animations": "^4.1.2",
    "@angular/common": "^4.0.0",
    "@angular/compiler": "^4.0.0",
    "@angular/core": "^4.0.0",
    "@angular/forms": "^4.0.0",
    "@angular/http": "^4.0.0",
    "@angular/platform-browser": "^4.0.0",
    "@angular/platform-browser-dynamic": "^4.0.0",
    "@angular/router": "^4.0.0",
    "bootstrap": "^3.3.7",
    "core-js": "^2.4.1",
    "jquery": "^3.2.1",
    "mds.persian.calendar": "^0.9.69",
    "rxjs": "^5.1.0",
    "zone.js": "^0.8.4"
  }
}

I've successfully published it on npm
Now I'm looking to use this package in another angular 4 project.
So I've installed the package using

npm install mds.angular.bootstrap.datetimepicker --save

Then I proceed to implement it as follows:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { MdsDatetimePickerModule } from 'mds.angular.bootstrap.datetimepicker';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [ AppComponent ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    MdsDatetimePickerModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Things were going smoothly until I had to import IDate from the

mds.angular.bootstrap.datetimepicker
package for usage within my component.
However, upon attempting to do so, an exception was thrown:

ERROR in D:/Sources/sample/src/app/app.component.ts (2,23): Cannot find module 'date.interface'.


import { Component } from '@angular/core';
import { IDate } from 'date.interface'; //ERROR

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Mds Angular Bootstrap DateTimePicker';
  viewInit = false;

  inLinePersianDateTimePicker = '';
  inlinePersianDatePickerChanged(selectedDate: IDate) {
    if (!this.viewInit) return;
    this.inLinePersianDateTimePicker = selectedDate.formatString;
  }

  inLineGregorianDateTimePicker = '';
  inlineGregorianDatePickerChanged(selectedDate: IDate) {
    if (!this.viewInit) return;
    this.inLineGregorianDateTimePicker = selectedDate.formatString;
  }

  popoverPersianDateTimePicker = '';
  popoverPersianDateTimePickerChanged(selectedDate: IDate) {
    if (!this.viewInit) return;
    this.popoverPersianDateTimePicker = selectedDate.formatString;
  }

  popoverGregorianDateTimePicker = '';
  popoverGregorianDateTimePickerChanged(selectedDate: IDate) {
    if (!this.viewInit) return;
    this.popoverGregorianDateTimePicker = selectedDate.formatString;
  }

  ngAfterViewInit() {
    this.viewInit = true;
  }
}

This is the IDate interface within the

mds.angular.bootstrap.datetimepicker
package

export interface IDate {
  year: number;
  month: number;
  day: number;
  hour: number;
  minute: number;
  second: number;
  millisecond: number;
  formatString: string;
}

How can I properly utilize the IDate interface in external applications?

Answer №1

After much searching, I have finally uncovered the solution:

To begin: Start by creating a file named index.ts (you can rename it if needed) and include an export statement for each type you wish to utilize from external libraries.

export * from "./mds-datetimePicker.module";
export * from "./services/mds-datetime-picker-resources.service";
export * from "./components/mds-datetime-picker.component";
export * from "./components/core/mds-datetime-picker-core.component";
export * from "./assests/date.interface";
export * from "./assests/day.interface";
export * from "./assests/mds-datetime-picker.utility";
export * from "./assests/rangeDate.interface";

Next: Open a command prompt and navigate to the directory containing your package.json file, then execute the following command:

tsc --declaration

You also have the option to use tsc -d. This command will compile the typescript files and generate corresponding *.d.ts files.

Finally: Within your package.json, insert the following lines:

"main": "./index.js",
"types": "./index.d.ts"

Now, all types declared in index.ts can be imported as shown below:

import { MdsDatetimePickerModule, IDate } from 'mds.angular.bootstrap.datetimepicker';

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

Tips for dynamically altering the data type of an object in Angular depending on a certain condition

I'm currently in the process of developing an online store and facing challenges with integrating a dynamic form system that can adapt based on the type of product being added to the store. For instance, if I select the 'Clothing' category, ...

The return type of TypeScript functions is not being properly documented

Can you help me understand why the result object is showing as type {foo: unknown, bar: unknown, baz: unknown}, when I believe it should actually be of type {foo: number, bar: boolean, baz: string} export function apply<A, B extends {[P in keyof A]: B ...

Encountering a Content Security Policy error upon deploying a jhipster Angular application on Heroku and attempting to access Marketo REST APIs

I developed a monolith application using jhipster, based on Angular. I leveraged Angular to make http calls to the Marketo REST APIs and everything was running smoothly in my local environment. I was able to successfully generate an access token, retriev ...

Would you like to learn how to display the value of a different component in this specific Angular 2 code and beyond

Hey there, I need your expertise to review this code and help me locate the issue causing variable "itemCount" to not display any value in about.component.html while everything works fine in home.component.html. I am attempting to only show "itemCount" in ...

Discovering an array containing a specific value and transforming it to another array in Angular 8

I have an array called this.data which contains a list of platforms. Each platform has its own set of section lists, where a section list consists of values like sectionName, sectionid, and sectionVal. Now, my goal is to replace the old sectionList with a ...

Unit testing Jasmine using the BehaviorSubject in Angular

I have a service set up like this: calendar-domain.service.ts @Injectable() export class CalendarDomainService { private _calendarWeek = new BehaviorSubject<CalendarWeekTo | null>(null); get calendarWeek$(): Observable<CalendarWeekTo | null&g ...

Error alert: Ionic detected a SyntaxError due to a missing closing parenthesis on the emulator

When using Ionic, I encountered an error Uncaught SyntaxError: missing ) after argument list on the emulator, but everything runs smoothly with the serve command: Fetch(what, callbackf) { return this.woo.getAsync(what).then( (result)=> { th ...

Incompatible TypeScript function declarations

Here's an example code snippet that is causing me some confusion due to an error. In the setFilter method, I have specified the type of T as Product. Therefore, I would expect to be able to successfully set the filter, since both T and Product share ...

What steps can be taken to address the InvalidPipeArgument error when working with dates?

When attempting to format a date in a specific way using the pipe date, I encountered an error: Uncaught Error: InvalidPipeArgument: 'Unable to convert "25/01/2019" into a date' for pipe 'e' at Xe (main.fc4242d58c261cf678ad.js:1) ...

What causes recaptcha to automatically trigger a GET request within an Angular 4 application?

I am in the process of integrating Google's Recaptcha into my Angular 4 application to enhance the security of my login and protect against brute force attacks. To do this, I have installed the angular2-recaptcha plugin (https://www.npmjs.com/package/ ...

Trouble arises when attempting to modify a property inherited from a parent class in TypeScript while

I've defined a base class like the following: import Vue from "vue"; class ComponentBase extends Vue { constructor() { super(); this.left = 100; this.top = 100; this.isSelected = false; } public left: numb ...

Update the mandatory fields in the required interface to extend to another interface, while ensuring that all subfields become

Currently, I have defined 2 interfaces: interface BattleSkills { strength: number; armor: number; magic_resistance: number; health: number; mana: number; intelligence: number; accuracy: number; agility: number; critical_damage: number; } ...

What is the best way to create a customized dropdown menu with selectable options in Android forms?

Currently, I am facing a situation where I have an AsyncTask class running to perform a GET request and retrieve a JSONArray from my server. This data is then displayed in a drop-down/select-option/listView horizontally. The user can filter this list by ty ...

What is the reason for storing a base64 string as an Object in a MongoDB database?

I am facing an issue with storing a product detail on the mongoDB database. When I try to save it, mongoDB stores a property imageSrc as an object instead of a string. Here is my database This is my angular service And this is my express server request ...

Ensuring Redirection to Login Page Upon Refresh in React Router Dom

I have encountered a scenario where the customer needs to be directed to the login screen upon Browser refresh. For example: import "./styles.css"; import { Route, Routes, BrowserRouter as Router, Outlet, Link } from "react-router- ...

Steps to resolve the Angular observable error

I am trying to remove the currently logged-in user using a filter method, but I encountered an error: Type 'Subscription' is missing the following properties from type 'Observable[]>': _isScalar, source, operator, lift, and 6 more ...

Traverse the elements of a BehaviorSubject named Layer_Template

I am currently facing an issue with displaying data from my BehaviorSubject. I have come across a way to iterate through a BehaviorSubject using asyncpipe which subscribes to the Observable SERVICE todo.service.ts @Injectable() export class TodoService ...

Adding a unique font to the themeprovider within styled components: A step-by-step guide

In the process of developing a React application using material-ui styled-components along with TypeScript. The task at hand is to incorporate a custom font into my styled components, but I'm facing challenges in making it functional. My initial ste ...

Using template expressions to access properties that contain spaces

Here is the code structure that I am working with: "name": { "age": [ { "data": { "how old": "23" } }, One of my JSON keys has a space in it. How can I access this pr ...

Are there type declarations in TypeScript for the InputEvent?

Wondering if there is a @types/* module that offers type definitions for the InputEvent object? For more information about InputEvent, you can visit this link. ...