Create a .d.ts file for a custom JavaScript file

I am working on an application written in JavaScript and considering incorporating TypeScript for a new feature. Currently, I have a base class defined in JavaScript as shown below:

// base.js

module.exports = function BaseClass () {
    // ... ...
};

My goal is to create a class in TypeScript that extends this base class like so:

// sub.ts
import Base from "./base.js";
class Sub extends Base {
    // ... ...
}

However, upon implementing this, I encountered an error in sub.ts stating:

Type "Base" is not a constructor function type.

I am curious as to why this error is occurring. Could it be due to the absence of a .d.ts file for my base.js? If that's the case, how can I generate the necessary declaration file for base.js and where should I place it?

Answer №1

Could the absence of a .d.ts file for my base.js be causing this issue?

Absolutely.

If that's the case, how can I generate the necessary definitely typed file for base.js?

Simply create base.d.ts:

declare class Base {
}

Where should this file be placed?

Right next to base.js.

Answer №2

Here is a complete example, inspired by @basarat's solution:

// data.js
var information = {
  "values": [
    {
      "value": "a",
    },
    {
      "value": "b",
    }
  ],
  "year" : 2018
  }

export { information }


export declare class information {
    static values : any[];
    static year   : number
}


// app.ts
import { information } from './data.js';

// data.values.filter() // Autocompletion for Array methods should display in the IDE
// data.year.toFixed(1) // Autocompletion for Number methods should show in the IDE

Verified on an Angular 6 project using: TypeScript V2.9.2.

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

What is the best way to create a React component that renders a class component as a functional component?

My Objective: At the moment, I am in the process of developing an AuthUserRole HOC component to manage user roles like Manager and Employee. However, I encountered a tutorial that uses a functional component to return a class component as referenced here. ...

What could be causing the undefined properties of my input variables in Angular?

Currently, I am fetching data from a service within the app component and passing it down to a child component using @Input. Oddly enough, when I log the data in ngOnInit, it appears correctly in the child component. However, when I try to assign it to a v ...

Develop a FormGroup through the implementation of a reusable component structure

I am in need of creating multiple FormGroups with the same definition. To achieve this, I have set up a constant variable with the following structure: export const predefinedFormGroup = { 'field1': new FormControl(null, [Validators.required]) ...

AngularJS ng-model not refreshing

One of the features in my application is a Font Awesome icon picker that allows employees to easily access different icons without having to search for their codes online. However, I am facing an issue where clicking on an icon does not update the ng-mode ...

What is the process for including a custom Jasmine matcher definition in Typescript?

I've been searching around for information on creating custom Jasmine matchers using TypeScript and it seems like a common issue. However, none of the solutions I've come across have worked for me. My setup includes: { "typescript": "2.3.2", ...

The partial template is not functioning as anticipated

Introducing an interface designed to accept two templates, with the resulting function being a partial of one of them (similar to React-Redux): export type IState<TState, TOwnProps> = { connect: (mapStateToProps: MapStateToProps<TState, Parti ...

Tips for creating a universal function for two interlinked types

My goal is to establish an abstract relationship between different sub-types of Message and Response, allowing for a generic function that takes a Message as input and returns a corresponding Response. Specifically, when the function is called with type Me ...

The error message states that the property 'registerUser' is not found on the class 'UserController'

In the controller file, I exported two functions (registerUser and loginUser) as default. No errors were thrown at that stage, but when attempting to access the routes, an error occurred stating - Property 'registerUser' does not exist on type &a ...

Encountering an ERROR during the compilation of ./src/polyfills.ts while running ng test - Angular 6. The module build

I encountered a problem in an angular project I am working on where the karma.config was missing. To resolve this, I manually added it and attempted to run the test using the command ng test. However, during the execution, an error message appeared: [./src ...

Exploring the potential of the forkJoin operator in Angular 4's Observable

I'm currently facing a challenge that involves retrieving both administrators and professionals from the "users" collection using AngularFire's latest version. I am utilizing Observables for this task. My goal is to make two parallel requests an ...

Choose an option from a selection and showcase it

I need to implement a modal that displays a list of different sounds for the user to choose from. Once they select a sound, it should be displayed on the main page. Here is the code snippet for the modal page: <ion-content text-center> <ion-ca ...

Unable to instantiate a Vue reference with a potential null type

When working in Vue v3, I encountered a situation where I needed to create a ref with a type that could possibly be null. This specific scenario in my app involves data that starts off as null and then gets populated after loading completes. Just to illus ...

Utilize Knex to retrieve data from the req.query

express and knex have been giving me some trouble; I am struggling to get this endpoint working using req.querys (response from express), even though it worked fine when I used req.params. Express: app.get(`/actor`, async (req: Request, res: Response) =&g ...

Properly configuring paths in react-native for smooth navigation

When working on my React-Native project, I noticed that my import paths look something like this: import { ScreenContainer, SLButton, SLTextInput, } from '../../../../../components'; import { KeyBoardTypes } from '../../../../../enums ...

What could be the reason for receiving the error message "NgModule' is not found" even after executing the command "npm i @types/node --global"?

Even though I tried following the suggestions provided in this Stack Overflow thread, I am still encountering the error "TypeScript error in Angular2 code: Cannot find name 'module'". My development environment consists of Angular 5 and npm versi ...

I am deciding between using CommonJS or ES module for my sub packages in a Yarn workspace for my Next.js project. Which one

Currently working on a Next.js monorepo project using TypeScript and yarn workspace. Within the yarn workspace, there are two packages: /web and /api. The /web package is a next.js project, while /api serves as a shared subpackage utilized by /web. /my-pr ...

Ways to avoid Next.js from creating a singleton class/object multiple times

I developed a unique analytics tool that looks like this: class Analytics { data: Record<string, IData>; constructor() { this.data = {}; } setPaths(identifier: string) { if (!this.data[identifier]) this.da ...

Setting up TypeScript compilation for TS modules in an AngularJs application: A comprehensive guide

After conducting a test, it has come to my attention that TypeScript 2.6.2 imposes a requirement where imported elements need to be used in a new before the module is referenced in a require. The test is based on the following code snippets extracted from ...

The data type 'void | Observable<any>' cannot be assigned to the type 'ObservableInput<any>'. Specifically, the type 'void' cannot be assigned to 'ObservableInput<any>'

I encountered an error in my visual studio code: Argument of type '(query: string) => void | Observable' is not assignable to parameter of type '(value: string, index: number) => ObservableInput'. Type 'void | Observable& ...

Develop a custom data structure by combining different key elements with diverse property values

Within my coding dilemma lies a Union of strings: type Keys = 'a' | 'b' | 'c' My desire is to craft an object type using these union keys, with the flexibility for assigned values in that type. The typical approach involves ...