JavaScript library experiencing import issues with Typescript custom type

Working on a Vue project with TypeScript, I encountered an issue when importing a custom type created for the vue-numeral-filter package. The error message received is as follows:

ERROR in /Users/bmartins/Development/app-invest/src/main.ts(14,30): 14:30 Could not find a declaration file for module 'vue-numeral-filter'. '/Users/bmartins/Development/app-invest/node_modules/vue-numeral-filter/dist/vue-numeral-filter.es.js' implicitly has an 'any' type. Try

npm install @types/vue-numeral-filter
if it exists or add a new declaration (.d.ts) file containing
declare module 'vue-numeral-filter';

In my main.ts file, the imports are as follows:

import Vue from 'vue';
import App from './App.vue';
import Vuetify from 'vuetify';
import vuetify from './plugins/vuetify';
import router from './router';
import VueApexCharts from 'vue-apexcharts';
import Vuex from 'vuex';
import store from './store';
import { mockStore } from './test/mock/store';
import * as moment from 'moment';
import 'moment/locale/pt-br';
import VueMoment from 'vue-moment';
import { API_URL, PRODUCT_TYPES } from './store/constants';
import VueNumeralFilter from 'vue-numeral-filter';

Vue.component('apexchart', VueApexCharts);

Vue.use(Vuetify);
Vue.use(Vuex);
Vue.use(VueNumeralFilter, { locale: 'pt-br' });
Vue.use(VueMoment, {
  moment,
});

For the custom type, I created a folder structure as follows:

App 
|_ src 
|_ types    
   |_ vue-numeral-filter
        |_ index.d.ts

Folder Structure

The index.d.ts file I created based on the @types/vue-moment looks like this:

import Numeral from 'numeral';
import { PluginObject } from 'vue';

declare namespace VueNumeralFilterPlugin {
  interface Options {
    // The optional (self-maintained) numeral instance
    numeral?: Numeral;
  }
  interface VueStatic extends Numeral {
    (inp?: Numeral, format?: string): string;
    (inp?: Numeral): string;
  }
}

declare module 'vue-numeral-filter' {
  interface Vue {
    $numeral: VueNumeralFilterPlugin.VueStatic;
  }
}

type VueNumeralFilter = PluginObject<undefined>;

declare const VueNumeralFilter: VueNumeralFilter;
export = VueNumeralFilter;

Finally, I made changes to the tsconfig.json file:

{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "strict": true,
    "jsx": "preserve",
    "importHelpers": true,
    "moduleResolution": "node",
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "sourceMap": true,
    "baseUrl": ".",
    "typeRoots": [
      "./types"
    ],
    "types": [
      "webpack-env",
      "vue-numeral-filter",
      "vuetify-form-base"
    ],
    "paths": {
      "@/*": [
        "src/*"
      ]
    },
    "lib": [
      "esnext",
      "dom",
      "dom.iterable",
      "scripthost"
    ]
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.tsx",
    "src/**/*.vue",
    "tests/**/*.ts",
    "tests/**/*.tsx"
  ],
  "exclude": [
    "node_modules"
  ]
}

Despite reading this post TypeScript 2: custom typings for untyped npm module multiple times for guidance, I am still struggling to resolve the issue. Any assistance would be greatly appreciated.

Answer №1

In Typescript, dealing with type definition files can be a bit tricky. It's common to accidentally write something that TypeScript interprets as a module instead of a declaration file. This can lead to issues where TypeScript expects you to import types directly from the file, rather than recognizing the embedded type declaration.

It seems like there might be an error in your type definition file. Specifically, the presence of import statements outside the module declaration could be causing TypeScript to identify it as a module. Moving these import statements inside the declare { ... } block might resolve the issue.

Additionally, the typeRoots and types entries in your tsconfig.json file appear to be too restrictive. While this may not be the root cause of the problem, removing these restrictions could prevent difficulties in the future when installing third-party types.

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

Determining if an object aligns with a specific type in Typescript

Hey there, I've got a little dilemma. Imagine I have a type called A: type A = { prop1: string, prop2: { prop3: string } } Now, let's say I'm getting a JSON object from an outside service and I need to check if that JSO ...

What is the best way to determine if a user is currently in a voice channel using discord.js?

Is there a way for me to determine if a user is currently linked to a voice channel? I am trying to implement a command that allows me to remove a user from a voice channel, and here is how I am attempting to check: const user: any = interaction.options.ge ...

Utilizing Dynamic Components and the Event Emitter Feature in Angular Version 5

As a newcomer to Angular, I am currently grappling with the concept of dynamic components within my project. Specifically, I am working on implementing functionality where a user can select a row in a component and then click a button to open a modal (cont ...

What is the best way to combine the attributes of multiple objects within a union type?

I have a clearly defined schema type Schema = { a: { a: 1 } b: { b: 2 } } I am in need of a function that can generate objects that adhere to multiple schemas. function createObject<K extends keyof Schema>(schema: Array<K>, obj: Sche ...

Combine the values in the array with the input

I received some data from the back-end which is being written to a form, and it's in the form of an array of objects Below is the code snippet: this.companyDetailsForm = new FormGroup({ directors : new FormControl(response?.companyDirectors) ...

Ways to display a variable prior to making an axios request

I have a get request that saves the result in a variable named name_student. How can I access this variable in other methods? Or how should I declare it? Here is the code snippet: getStudent(){ axios.get('https://backunizoom.herokuapp.com/student/2 ...

Setting up tsconfig.json to enable support for either string literals or string templates involves adjusting the compiler options

After utilizing swagger codgen with the typescript-aurelia template to create API code, I noticed that a significant amount of string literals were being used in the resulting code. Despite encountering errors when running the transpiler tsc from the comma ...

Tips for accessing the Vue store from a component while implementing it with a router

I'm encountering an issue with accessing a variable in the Vuex store from a component. Despite trying to access the value, it consistently appears as empty. I am utilizing routers for navigation between components. router.js const routes = [ { ...

Arrange information in table format using Angular Material

I have successfully set up a component in Angular and Material. The data I need is accessible through the BitBucket status API: However, I am facing an issue with enabling column sorting for all 3 columns using default settings. Any help or guidance on th ...

Taking advantage of Input decorator to access several properties in Angular 2

I am currently working on a component that is designed to receive two inputs through its selector. However, I would like to make it flexible enough to accept any number of inputs from various components. Initially, I tried using a single @Input() decorator ...

The absence of text is not displayed in an empty slot of a Buefy table

Currently, I am working on a Nuxt project with Buefy implementation. I attempted to create a table with an #empty slot that displays a message when no data is available. However, my code does not seem to be working as expected. If you refer to the Buefy do ...

Can anyone provide guidance on showcasing data received from Laravel resource in a Vue Component?

I've been honing my skills in Vue and am grappling with how to manage data passing. Within my Vue component, I have a link that looks like this: <a class="btn btn-success" :href="'/projectpage/' + project.id">Bid</a>, and I found ...

Tips for verifying internet connectivity and accessing stored data in localstorage

I'm working on my home.ts file and I need to use localStorage items when the internet connection is offline. However, I am encountering numerous errors when trying to add an IF condition in my code. Specifically, I want to access the getItem method be ...

The TypeScript compilation failed for the Next.js module

Working on a project using Next.js with typescript. The dev server was running smoothly, and I could see frontend changes instantly. However, after modifying the next.config.js file and restarting the server (later reverting the changes), compilation issue ...

Utilizing JavaScript files within Angular2 components: A guide

I need to insert a widget that runs on load. Typically, in a regular HTML page, I would include the script: <script src="rectangleDrawing.js"></script> Then, I would add a div as a placeholder: <div name="rectangle></div> The is ...

Creating a class in TypeScript involves declaring a method that takes a parameter of type string, which matches the property name of a specific derived class type

I am working on a scenario where I have a base class containing a method that can be called from derived classes. In this method, you provide the name of a property from the derived class which must be of a specific type. The method then performs an operat ...

Utilize the identical function within the reducer for numerous mat-slide-toggle and checkboxes in component.html

I'm currently diving into the world of Angular and ngrx while tackling a project focused on enabling users to create forms. In this project, users can add various form elements (such as labels, text fields, dropdown menus, checkboxes, etc.) from a sid ...

Utilizing v-slot:item in a custom datatable component with Vuetify

In the creation of a custom datatable component, my Table.vue file is displayed as follows: <template> <div> <v-data-table :headers="headers" :items="items" :search="se ...

typescript what type of functionality do dynamic class methods provide

I'm currently working on building a class that creates dynamic methods during the constructor stage. While everything is functioning properly, I've encountered an issue with VS Code's auto suggestion not recognizing these dynamic methods. Ho ...

A step-by-step guide on building a parent layout in VueJS

I have a component structure and code that includes two layouts: UserLayout and OrganizationLayout. The OrganizationLayout is similar to UserLayout, with the only difference being a navigation component in the header. Both layouts require user profile dat ...