djipco / webmidi

Tame the Web MIDI API. Send and receive MIDI messages with ease. Control instruments with user-friendly functions (playNote, sendPitchBend, etc.). React to MIDI input with simple event listeners (noteon, pitchbend, controlchange, etc.).
Apache License 2.0
1.53k stars 115 forks source link

connected/disconnected event emiter not properly exported #226

Closed glend1 closed 2 years ago

glend1 commented 2 years ago

thought i had a issue open for this, but i can't seem to find it so im reposting. sorry if im just being blind.

when I do the following

WebMidi.addListener("connected", (e) => { console.log(e.target.name)});

i get the following typescript error

Property 'name' does not exist on type 'Input | WebMidi | InputChannel | Output'.
    Property 'name' does not exist on type 'WebMidi'.ts(2339)
djipco commented 2 years ago

I just tried the code below in Node.js and I'm not getting any errors with v3.0.10:

const {WebMidi} = require("webmidi");
WebMidi.addListener("connected", e => console.log(e.target.name));
WebMidi.enable();

Can you provide a little more info about the environment where you get that error?

glend1 commented 2 years ago

I am using Next.js which doesn't like using require so I converted your code to an import (you are able to bypass as shown in the following code snippet with export {})

//import {WebMidi} from "webmidi";
const {WebMidi} = require("webmidi");
WebMidi.addListener("connected", e => console.log(e.target.name));
WebMidi.enable();

export{}

however, with require I notice that e is any.

djipco commented 2 years ago

There must be something different in your environment because it works for me. Your code example ran fine in a demo Next.js project. I tried with require and import and both worked fine.

djipco commented 2 years ago

Hold on... I think I found the issue. Let me get back to you.

djipco commented 2 years ago

I took a deeper look at events and concluded that all events that are triggered by a port (Input or Output) needed their own type definitions for TypeScript. So, I have added a PortEvent type that extends the basic Event type. The PortEvent type has a port property that points to the Input of Output port.

So, in your case, you should be able to use e.port.name just like before.

This will also help when adding a listener to an InputChannel. In this case, e.port will point to the Input object while e.target will point to the InputChannel object.

This change is available right now in version 3.0.11.