language-tools icon indicating copy to clipboard operation
language-tools copied to clipboard

How do I type custom events for a package?

Open ghostdevv opened this issue 4 years ago • 4 comments

I was wondering what would be the best way to type custom events for a package, puru was recently doing this and now I am too - while you can type the events like this (https://discord.com/channels/457912077277855764/728292755087818924/908761587660255313) I don't know of a way to export those types out of a package and have the language server pick up on that

Any ideas?

ghostdevv avatar Nov 16 '21 12:11 ghostdevv

I guess you talking about custom events in the context of actions. If not, the solution below doesn't apply.

This came up in Discord, too, recently, here is the thread: https://discord.com/channels/457912077277855764/897113912422580274 . It didn't seem to work for that person but I didn't look into why exactly. If you could try the steps and report back if it works that would be great. The steps (roughly):

  1. create a types.d.ts (or whatever you call it) inside your package, enhance the typings like in your Discord link - make sure to keep this an ambient type, so no top level imports/exports allowed
  2. import that file in your index.d.ts which is the default types export like import './types.d.ts';

If you have your package publicly somewhere, I could take a look.

I also plan on introducing support for typing the events of an action on the action function itself. So basically you would be able to hint at typescript that by applying an action to a DOM element that element now has additional attributes/events that can be passed to it. This depends on changes to Svelte core and a pending rewrite of svelte2tsx, so this will take a little while.

dummdidumm avatar Nov 16 '21 13:11 dummdidumm

I wrote this package as a test, it has a testAction which emits a custom event called test, I don't get intellisense suggesting that test is a event (like I do with other events) but the actual typings appear to be working which is awesome:

Screenshot from 2021-11-19 09-39-10

ghostdevv avatar Nov 19 '21 09:11 ghostdevv

Yes, autocomplete intellisense is missing because that needs some more work on our side to make it show up (not sure how we can get there without showing all other redundant completions). Good to hear that this works, I guess we need to document the way how to do this once the rewrite happened and we are in a more stable state to officially recommend the best way to do this.

dummdidumm avatar Nov 19 '21 10:11 dummdidumm

Yea would be awesome to be able to do this but glad to know that this does work just missing intellisense - how would you recommend doing this with sveltekit package for example?

ghostdevv avatar Nov 19 '21 21:11 ghostdevv