Franc
Franc

Reputation: 5496

Adding a method to a Typescript class using prototype

enter image description here

I don't seem to be able to add a method to my Typescript class using prototype. Visual Studio warns me that the function does not exist in the the target type.

I read something about declaring an additional interface for my type that would include the definition of the method I want to add, but it's not very clear to me how I should do this after importing my type with import. In fact, I cannot simply do:

import { EcommerceCartItem } from "../classes/EcommerceCartItem";

interface EcommerceCartItem {
    myMethod: any
}

EcommerceCartItem.prototype.myMethod = function () {
    return null;
};

...because the import declaration conflicts with the local declaration of EcommerceCartItem. So how should I go about it?

Upvotes: 0

Views: 63

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249586

You must declare the interface in the appropriate module for it to count as an augmentation:

import { EcommerceCartItem } from "../classes/EcommerceCartItem";
declare module "../classes/EcommerceCartItem" {
    interface EcommerceCartItem {
        myMethod: any
    }
}

EcommerceCartItem.prototype.myMethod = function () {
    return null;
};

Upvotes: 1

Related Questions