Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript module augmentation across multiple modules

I'm attempting to modify the prototype of an object inside another module (similar to as demonstrated here). However, module augmentation seems to only work when augmenting an object declared in a required file in the same module rather than another module.

For example, I have a class, TestClass:

// some-module/TestClass.ts

export class TestClass {
    someValue: string = "hi";
    someFunc(): number {
        return 5;
    }
}

And in the same module, I have this:

// some-module/index.ts

import { TestClass } from "./TestClass";

declare module "./TestClass" {
    interface TestClass {
        doSomethingElse(): void;
    }
}

TestClass.prototype.doSomethingElse = function(): void {
    console.log("Something else");
};

This works fine. However, if I move TestClass to another module (test-module/TestClass.ts) and modify the code appropriately like this, it gives me the error 'TestClass' only refers to a type, but being used as a value here. whenever I try and access TestClass.

// some-module/index.ts

import { TestClass } from "test-project";

declare module "test-project" {
    interface TestClass {
        doSomethingElse(): void;
    }
}

TestClass.prototype.doSomethingElse = function(): void {
    console.log("Something else");
};

I'm using NodeJS module resolution with CommonJS.

Any help would be much appreciated.

like image 718
Zoyt Avatar asked Sep 08 '25 11:09

Zoyt


1 Answers

It's because you need to import the whole module with import * instead of just the class you need, see https://github.com/Microsoft/TypeScript/issues/9015

like image 52
nbransby Avatar answered Sep 10 '25 08:09

nbransby