youra_halloween
youra_halloween

Reputation: 63

TypeScript Add method to prototype

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

Upvotes: 2

Views: 3375

Answers (1)

youra_halloween
youra_halloween

Reputation: 63

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 = () => { /* ... */};

Upvotes: 4

Related Questions