[SOLVED] typescript copy function and preserve types


I am using p5.js with typescrtip.

In p5.js you have a p5 object where you can call

let p5: P5; // it is assigned somwhere else but this does not matter for this question

p5.createCanves(400, 400);
p5.line(0, 0, 400, 400);

to draw a line from the top left corner to the bottom right corner of a white canves.

now I am trying to call these methodes without the p5. in front.

so far I have tried this:

let p5: P5;

const createCanvas = p5.createCanvas;
const background = p5.background;
const line = p5.line;

// or

const createCanvas = (() => { return p.createCanvas; })();
const background = (() => { return p.background; })();
const line = (() => { return p.line; })();

but p5.js does not allow these methodes to be acsessed before the methode p5.setup is called, and thus I am not allowed to assign the methodes to a variable.

next I tried just calling the methode:

const createCanvas = (x: number, y: number) => p5.createCanvas(x, y);
const background = (value: string) => p5.background(value);
const line = (x1: number, y1: number, x2: number, y2: number) => p5.line(x1, y1, x2, y2);

but this aproach is anoying if I have to do this with every function and I cannot reproduce overloads. For example the background methode has the following 6 signatures:

background(color: Color)
background(colorstring: string, a?: number | undefined)
background(gray: number, a?: number | undefined)
background(v1: number, v2: number, v3: number, a?: number | undefined)
background(values: number[])
background(image: Image, a?: number | undefined)

I have no idea how I could keep the Types and assign it to an variable. If there is a way pleas post an answer. My aproach would be

const backgroud = (color: Color)
                  (colorstring: string, a?: number | undefined)
                  (gray: number, a?: number | undefined)
                  (v1: number, v2: number, v3: number, a?: number | undefined)
                  (values: number[])
                  (image: Image, a?: number | undefined) => {
  if(color) return p5.background(color)
  if(colorstring) return p5.background(colorstring, number)
  if(gray) return p5.background(gray, a)
  if(v1) return p5.background(v1, v2, v3, a)
  if(values) return p5.background(values)
  if(image) return p5.background(image, a)

but this is obviously not valide Typescript

I also tried to somehow import the methodes in an other file

import {p5.*} from "./index"

but that is not possible as far as I know

Is there an easier aproach to my problem or should I just give up and write that god tamn p5.?

And is there a way to combine these 6 signatures into 1 variable?


background function

rect function

you take a type from the library and assign it to a proxy arrow function.

Answered By – D Pro

Answer Checked By – Cary Denson (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *