2

There is a parent Object1. There is a child Object2. It turns out something like this class:

class Object1 {
   obj: Object2
}

I want to add a method to Object2. The class cannot be inherited because you will have to specify a new class name. So I'm trying to add a method in the following way:

class Object2 {
//Let's say there is such a property
    public name: string = 'asd';
}

interface Object2 {
    log: () => void
}

Object2.prototype.log = function () {
    console.log(this.name);
};

This code works!!!

But the point is that the Object2 class is the npm module of the package. I am importing the class. And everything stops working.

import { Object2 } from 'somepacket';

interface Object2 {
    log: () => void
}

Object2.prototype.log = function () {
    console.log(this.name);
};

And I am getting error: Import declaration conflicts with local declaration .ts (2440)

So what's the difference? The Object2 class is exported or is in the same file

2
  • You need to declare your type as an augmentation of the type exported by the package: import { Object2 } from 'somepacket'; declare module 'somepacket' { interface Object2 { log: () => void }} Commented Jan 11, 2021 at 5:23
  • Github Gist? My hacky solution is good but I'm 100% sure you cannot assign properties to non-declared interface/class/namespace. Commented Jan 11, 2021 at 15:16

1 Answer 1

4

Add a way to declare prototype modifications

src/MyType.ts:

export class MyType {
  existingMethod(): void;
}

src/MyTypeExtension.ts:

import {MyType} from './MyType';

declare module './MyType' {
  interface MyType {
    newMethod(): void;
  }
}

MyType.prototype.newMethod = () => { /* ... */};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.