简体   繁体   中英

Convert Javascript to Typescript when modifying a function through the variable reference

I am trying to convert a javascript code file to a typescript file, however, I have difficulties doing it when meeting to modify a function through the variable reference.

In javascript, the code was written as:

  Object.getPrototypeOf(ctx).rounded_rect = function(){

  }

where ctx is a canvas rendering context 2d varibale

How do I convert this code to typescript code? When I copy and paste it to typescript file, it shows error saying Property 'rounded_rect' does not exist on type 'CanvasRenderingContext2D'.

Also, what is this line of code called?

You need to extend the native prototype which requires a declaration first:

declare global {
   interface  CanvasRenderingContext2D {
      rounded_rect() : void;
   }
}

After that you can implement it:

CanvasRenderingContext2D.prototype.rounded_rect = function(){
 /*whatever*/
};

May refer to this similar answer...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM