Problem with JSDoc createGraphics() annotation in my sketch

When working with createGraphics() how do you set the correct JSDoc comment for the global variable var pg that is declared global outside of setup() and draw().

let say we start with a simple sketch like this:

var pg // Variable 'pg' implicitly has type 'any' in some locations where its type cannot be determined.

function setup() {
	createCanvas(500, 500)
	pg = createGraphics(width - 50, height - 50)
}

function draw() { 
	background(230)
	pg.background(40) // Variable 'pg' implicitly has an 'any' type.
	image(pg, 25, 25) // Variable 'pg' implicitly has an 'any' type
}

Right the editor have no idea about what pg is, it is an Any type. No idea about what method and properties are on that object.

/**
* @type {p5.Graphics} pg
*/
var pg

function setup() {
	createCanvas(500, 500)
	pg = createGraphics(width - 50, height - 50)
}

function draw() { 
	background(230)
	pg.background(40)
	image(pg, 25, 25)
}

Trying to set the @type above the global variable pg declaration doesn’t work, since Graphics doesn’t exist out here. 'global.p5' has no exported member 'Graphics'. but it is export from p5.Graphics.js.

So with that in mind, you can try to move it inside setup() by setting createGraphics() @returns to {p5.Graphics}.

var pg

function setup() {
	createCanvas(500, 500)
	/**
	* @returns {p5.Graphics} pg
	*/
	pg = createGraphics(width - 50, height - 50)
}

function draw() { 
	background(230)
	pg.background(40)
	image(pg, 25, 25)
}

Can someone help me to do this right? :smiley:

thanks.

1 Like

It doesn’t make much sense documenting 3rd-party libraries you import to your code.

For that we should grab their existing type definition files:

But in order to use such files you’ll probably need to switch to TypeScript:

Take a look at my previous posts w/ TS sketch examples: