Creating a library that works in both 'global' and ' instance' mode?

I am trying to create a new library that will work transparently in both global and instance modes.

I am using VSC with Typescript and have installed the nodes

  • p5
  • @types/p5

and updated the tsconfig.json file to include them

"include": [
    "src_ts/**/*",
    "./node_modules/p5/types/global.d.ts",
    "./node_modules/p5/types/p5.d.ts"
    // "libraries"
  ]
}

The core class is called S3D. An instance of this class will provide access to all the functionality of the library. So far all i have is this

class S3D {

    /** @hidden */ protected _renderer: p5.Renderer;
    /** @hidden */ protected _p: p5;
    /** @hidden */ protected _uid: string;
    /** @hidden */ protected _children: Array<Shape3D>;

    /**
     * @param name   a unique string identifier for this controller
     * @param p5c    reference to Processing canvas returned by the 
     *               'createCanvas' function
     * @param p      reference to the 'instance' variable
     *               (defaults to global instance)
     */
    constructor(name: string, p5c: p5.Renderer, p = p5.instance) {
        this._uid = name;
        this._children = [];
        this._p = p;
        this._renderer = p5c;
    }
}

At this stage I have 2 errors I need to resolve
protected _p: p5;

  • Cannot use namespace ‘p5’ as type ts(2709)

constructor(name: string, p5c: p5.Renderer, p = p5.instance) {

  • Property ‘instance’ does not exist on type ‘typeof import(“/Users/peter/Documents/js-workspace/Shapes3D/node_modules/p5/types/p5”)’.

The idea is that the class attribute _p will reference the instance variable or if no value passed the default (global) instance variable.

Any suggestions or ideas will be gratefully received.
:grinning_face:

Those aren’t errors but missing types defined in:

Parameter p’s default value p5.instance is valid at runtime regardless of what is defined or missing in “p5.d.ts”.

As a workaround, you can define an extra augmented “.d.ts” type file.
I’ve asked Gemini to write 1 for it:

import type p5 from 'p5';

declare module 'p5' {
  namespace p5 {
    /**
     * The global-mode `p5` sketch instance, or `null` otherwise.
     */
    var instance: p5 | null;
  }
}