5

I was wondering if there is any possibility to add some functions to the prototype of a class in Typescript.

My situation is as this: I've got a file with a class, e.g. image.ts:

export class Image {
    b64img: string;
}

This class is generated and so I can't add methods to it. I'm using this class in other generated classes, so creating a new class with extends Image is not possible for adding functions.

Is there any option that I can add a function to my class in a separated file so I could use it on all objects of the class Image?

Thanks

1 Answer 1

9

You can. You can extend it by defining an extension to the module it is defined in.

Create a file called image-extension.ts or something like that.

Now, if in that file you would import Image like this:

import { Image } from `image`;

declare module 'image' { // same name than in the import!
    export interface Image {
         newMethod: () => void;
    }
}

Image.prototype.newMethod = function() {
    console.log('new method');
}

Now, wherever you import this file, you can use that method:

import { Image } from 'image';
import 'image-extension'; // import just for side-effects

Of course, you can also add the declare module to a d.ts file, so it gets loaded automatically, and in another file add the true functions to the prototype, making sure that such a file gets loaded in your application

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your answer. If I don't import 'image-extension' the compiler doesn't raise any error but at runtime a message says newMethod is unknown. Is there a way to have a compiler error if the extension method is not correctly imported?

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.