Using imports with namespaces in TypeScript: A guide

I am facing an issue with two classes in separate files, where one extends from the other. The base class contains some import statements for node modules. I am confused as to why the derived class (located in a different file) is not recognizing the base class!

Could someone provide clarity on this matter?

// UtilBase.ts

/// <reference path="../typings/node.d.ts" />
/// <reference path="../typings/packages.d.ts" />

import * as path from "path"; // <---- THIS LINE BREAKS THE BUILD!!!!

namespace My.utils {

    export class UtilBase {

        protected fixPath(value: string): string {
            return value.replace('/', path.sep);
        }
   }
}

Also,

// UtilOne.ts
/// <reference path="UtilBase.ts" />

namespace My.utils {

    export class UtilOne extends My.utils.UtilBase {

    }
}

Upon compilation, I encounter the following error:

src/UtilOne.ts(6,47): error TS2339: Property 'UtilBase' does not 
exist on type 'typeof utils'

Answer №1

A solution utilizing namespaces (not the recommended approach)

To address the issue at hand, consider exporting your namespace:

// UtilBase.ts
import * as path from "path";
export namespace My.utils {
    export class UtilBase {
        protected fixPath(value: string): string {
            return value.replace('/', path.sep);
        }
   }
}

Following which, you can proceed with importing it:

// UtilOne.ts
import {My} from './UtilBase';
namespace My.utils {
    export class UtilOne extends My.utils.UtilBase {
    }
}

However, when prioritizing code organization, using both namespaces and (ES6) modules simultaneously is discouraged. Especially with Node.js where files are considered modules, favor avoiding namespaces.

Implementation of ES6 modules while omitting namespaces

TypeScript seamlessly integrates ES6 module syntax:

// UtilBase.ts
import * as path from "path";
export default class UtilBase {
    protected fixPath(value: string): string {
        return value.replace('/', path.sep);
    }
}

// UtilOne.ts
import UtilBase from './UtilBase';
export default class UtilOne extends UtilBase {
}

This method is highly recommended as ES6 modules mitigate naming clashes by allowing individual resource renaming upon importation.

It is fully compatible with Node.js environments.

For a comprehensive overview of ES6 modules syntax, refer to this enlightening article.

Replace /// <reference with a tsconfig.json file

Note: The usage of /// <reference syntax has been supplanted by the presence of a tsconfig.json file. An example tailored for Node.js entails:

// tsconfig.json
{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es6"
  },
  "exclude": [
    "node_modules"
  ]
}

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

Unable to locate the _app.js file within my Next.js project

After using "npx create-next-app" to set up my NextJs project, I came across a situation where I needed to define TransactionContext in _app.js. However, I encountered the issue that this file is not included in my project. Any assistance would be greatly ...

What is the reason for needing to specify event.target as an HTMLInputElement?

I am currently working on a codebase that uses Material Ui with theme overrides. As I set up my SettingContext and SettingsProvider, I find myself facing some syntax that is still unclear to me. Let's take a look at the following code snippet: const ...

Optimal method for retrieving data from a JSON object using the object's ID with a map

Can you teach me how to locate a json object in JavaScript? Here is a sample Json: { "Employees" : [ { "userId":"rirani", "jobTitleName":"Developer", "preferredFullName":"Romin Irani", "employeeCode":"E1", "region":"CA", "phoneNumber":"408-1234567", " ...

Is it possible for me to transfer a change to the worldwide namespace from my library?

I am looking to enhance an existing TypeScript type within the global namespace in my library and then expose it for use in other projects. Can this be done? Below is my current code: Promise.ts Promise.prototype.catchExtension = function<T>(this ...

Looking to receive detailed compiler error messages along with full imports in Visual Studio Code for TypeScript?

Currently, I am trying to edit a piece of typescript code in Visual Studio Code. However, I encountered a compiler error message that looks like this: The error states: Type 'import(\"c:/path/to/project/node_modules/@com.m...' is not assign ...

Utilizing the useSearchParams() function to retrieve live data in Next.js

Is there anyone who has successfully migrated from the pages router to the app router in Next.js? I am facing an issue with dynamic data migration. In the pages router, dynamic data is retrieved on a page using useRouter().query, but in the app router, it ...

"Frustrating issue with Firebase-admin dependency farmhash-modern resulting in webassembly error

Facing an issue while setting up firebase-admin SDK on my nextjs + TS project. Every time I try to call a SDK function, I encounter a webAssembly error. Specifically, when trying to configure a middleware for the server-side API and calling the verifyIdTok ...

State mutation not reflected in input field value update

During the development of a small project for educational purposes, I encountered an issue with updating the input value. Below is the simplified component causing this issue. function TipSelector({selections, onTipChanged}: {selections: TipSelectorItem[], ...

While deploying: Error 500 - The installation of dependencies was unsuccessful due to a request timeout

I'm encountering an issue while attempting to deploy my bot to Azure. Here's the command I used: az bot publish --name --proj-name "" --resource-group --code-dir "/path/to/my-app" --verbose --version v4 Unfortunately, it is timing out durin ...

What is the best way to add a header field to a response using NestJS?

I am attempting to create a login function in my code, but encountering an issue: @Post('login') async login(@Body() body: AuthDto, @Res() res: Response) { const loginResponse = await this.authService.login(body); console ...

The json.parse function can be used in JavaScript, but it is not compatible with Angular

Currently, I am in the process of converting an existing JavaScript application into Angular using TypeScript. In the original JavaScript application, I have a JSON data file that is successfully read during startup. However, when attempting to read the ex ...

I want to search through an array of tuples to find a specific value in the first index, and if there is a match, I need to return the value in the second index of the matching tuple

I am dealing with an array of tuples: var tuparray: [string, number][]; tuparray = [["0x123", 11], ["0x456", 7], ["0x789", 6]]; const addressmatch = tuparray.includes(manualAddress); In my function, I aim to verify if the t ...

Modify the title and go back dynamically in the document

I am currently working on a timer app where I want to dynamically change the document title. The app features a countdown timer, and during the countdown, I was able to display the timer in the document title successfully. However, once the countdown is co ...

Create a one-of-a-kind Angular 6 material table component featuring unique custom columns

My goal is to streamline the process of creating custom material tables by using a specialized table component that allows me to quickly generate unique tables for different data sources with built-in pagination and sorting. All I need to provide are the d ...

MyApp is encountering issues resolving all parameters

I'm encountering an issue that none of the other similar questions have been able to help me solve. Can anyone offer assistance? I've already attempted removing parameters one by one, but I'm still stuck. Can't resolve all parameters f ...

Angular 14: A collection and schematic must be provided for execution to proceed with the process

I've recently started learning angular. After installing the latest version, I created an app called "test" using the command ng new test. Next, I opened the app in Visual Studio Code and tried to create a new component by entering the command: ng g ...

Acquire data on the type from the returned outcome of a function

Below is a function that I am working with in the TypeScript playground: function myf(): Record<string, string> { return { prop1: "a", prop2: "b" } } This function is pure and simply returns a dictionary value. My goal is to ext ...

Managing the browser's "back" button functionality in React

I am currently using "react-dom-router v6.3.0" (strictly!) and I am struggling to figure out how to manage the browser's "back" button functionality. Specifically, I want to be able to detect when the user clicks the back button so that I can display ...

Setting up Next Js to display images from external domains

Encountering an issue with my next.config.js file while working on a project with Next.js in TypeScript. This project involves using ThreeJs, @react-three/fiber, and @react-three/drei libraries. Additionally, I need to include images from a specific public ...

A series of OR interfaces in TypeScript Interface

Imagine a scenario where there is a choice between multiple interfaces interface a {x:string} interface b {y:string} interface c {z:string} type all = a | b | c Now, consider an object fulfilling all by being of type c When you try to access the propert ...