0

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?

1 Answer 1

1

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;
};
Sign up to request clarification or add additional context in comments.

1 Comment

Oh, amazing, I didn't know this syntax. Thank you very much.

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.