I use p5.js but with typescript.
The structure of a p5 project:
let sketch = (p: p5) => {
p.setup = () => {setup(p)
};
p.draw = () => {draw(p)
};
};
new p5(sketch);
After reading this I defined my function setup and draw like this:
let slider: p5.Element;
function setup(p: p5): void {
p.createCanvas(400, 300);
slider = p.createSlider(0, 50, 50 / 2);
}
function draw(p: p5): void {
p.background(50);
p.fill(255);
p.noStroke();
p.ellipse(slider.value(), 50 / 2, 50, 50);
}
the code works but vs code underline slider.value() in red. This is normal because inside the the function draw we don’t know if slider is instantiated or not.
I would like to know if there a better way to writ this code. A way that doesn’t make VS code print this error.
the error printed by VS code:
No overload matches this call. Overload 1 of 2, ‘(x: number, y:
number, w: number, h?: number | undefined):
import(“c:/Users/pierreol.gendraud/Documents/create_doc/test2/node_modules/@types/p5/index.d.ts”)’,
gave the following error.
Argument of type ‘string | number’ is not assignable to parameter of type ‘number’.
Type ‘string’ is not assignable to type ‘number’. Overload 2 of 2, ‘(x: number, y: number, w: number, h: number, detail?: number |
undefined): void’, gave the following error.
Argument of type ‘string | number’ is not assignable to parameter of type ‘number’.
Type ‘string’ is not assignable to type ‘number’.
it doesn’t look like the problem comes from the fact can be uninstantiated. But this is the case. You can try to use slider.value() inside setup and no errors are raised