1

I am building an application in Typescript which relies on the P5.js library.

P5.js puts a lot of functions on the global namespace so they can be called in your webapp by just saying things like draw(), and ellipse(x, y, w, l) etc...

I am working in Webstorm and I want Webstorm to be able to perform its static analysis for me, so I have been adding the function names of P5.js to a p5.d.ts file (there is no p5.js Typescript definition file published yet), like:

declare var setup: () => void; declare var draw: () => void; declare var background: (color: number) => void; declare var stroke: (r: number, g: number, b: number) => void; ... 

However this is not ideal.

#1: These functions actually do return something - a P5 Object - which contains all these methods, though it's usually not used.

#2: I am still calling these methods throughout my application without any prefix or anything. This makes it a bit ambiguous as to where these functions are actually from.

There are more issues as well...

Can anyone offer some pointers on how to go about creating a .d.ts for a library like P5.js?

1

1 Answer 1

1

It's more natural to write these as functions. You can also declare an interface type to represent the common return type (I'm assuming they have it set up as a "chaining" API?)

declare function stroke(r: number, g: number, b: number): P5; declare function background(color: number): P5; interface P5 { stroke(r: number, g: number, b: number): P5; background(color: number): P5; } 

Unfortunately in TypeScript there isn't a way to say "Make this part of the global scope at the same time", so you'll have to duplicate these definitions.

Regarding #2, well, that's P5's problem? I would see if the P5 documentation provides for a smarter way to invoke the functions. Putting a bunch of stuff in the global scope isn't a common pattern for JS libraries anymore so there's probably some other way to do it.

Update

Yes apparently there is another way to use P5.js functions without polluting the global namespace.

Sign up to request clarification or add additional context in comments.

1 Comment

If you are putting the functions in the interface, do you also have to declare them?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.