Jeremy
Jeremy

Reputation: 157

Add function to class from another file in Typescript

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

Upvotes: 5

Views: 4697

Answers (1)

Oscar Paz
Oscar Paz

Reputation: 18292

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

Upvotes: 9

Related Questions