1

I am using p5.js and was wondering if I could use Typescript to destructure all the the properties in the p5 object. Currently my code looks something like this:

const sketch2 = (p5: P5) => {
  p5.setup = () => {
    const canvas = p5.createCanvas(200, 200);
  };

  p5.draw = () => {
    p5.fill(0);
    p5.ellipse(100, 100, 80, 80);
  };
};

I could do destructure every property but that could be quite tedious:

const sketch2 = (p5: P5) => {
  let { setup, createCanvas, draw, fill, ellipse } = p5;

  setup = () => {
    const canvas = createCanvas(200, 200);
  };

  draw = () => {
    fill(0);
    ellipse(100, 100, 80, 80);
  };
};

Could I use Typescript to destructure all the properties into the scope without naming them one by one?

sergmister
  • 185
  • 3
  • 12
  • When destructuring an object you have to destructure it into smaller, individually named pieces. Verbosity and destructuring come hand in hand. – Terry Jan 10 '22 at 19:56
  • Does this answer your question? [How do I destructure all properties into the current scope/closure in ES2015?](https://stackoverflow.com/questions/31907970/how-do-i-destructure-all-properties-into-the-current-scope-closure-in-es2015) – Christoph Lütjen Jan 10 '22 at 19:56
  • Not really, I am wondering if Typescript has anything to deal with this. – sergmister Jan 10 '22 at 19:57
  • Not an answer, but you could simplify to `const sketch2 = ({ setup, createCanvas, draw, fill, ellipse }: P5) => {` – Christoph Lütjen Jan 10 '22 at 20:25
  • By doing `let { setup /* ... */ } = p5; setup = somethingElse;` you'll alter only the value of your own, just declared variable `setup`, *not* the the `setup` property of the `p5` object -this will stay the same. – mbojko Jan 10 '22 at 21:03

1 Answers1

0

Use this line:

Object.entries(p5).forEach(([key, value]) => window[key] = value);

See the Example here.

  • if you are looking for a scoped variable, I have to say there is no way to achieve that.
Mahdi Zarei
  • 5,644
  • 7
  • 24
  • 54