Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Generics support #49

Open
ChrRubin opened this issue Oct 17, 2021 · 2 comments
Open

Generics support #49

ChrRubin opened this issue Oct 17, 2021 · 2 comments
Labels
enhancement New feature or request

Comments

@ChrRubin
Copy link

ChrRubin commented Oct 17, 2021

Would it be possible to introduce TypeScript generic type parameters support? TS recognizes @template tags from JSDoc annotations for type parameters, if that would be of any help.

From what I've tested, sveld would currently generate prop and slot typings with the type parameter(s) included, but because the exported class and interface do not have a type parameter list, it is invalid.

@metonym
Copy link
Collaborator

metonym commented Oct 18, 2021

I like this idea.

Could you illustrate a use case?

One that comes to mind would be a generic for a prop, but I'm curious how it'd look for events/slots.

import type { TypeaheadProps } from "svelte-typeahead/src/Typeahead.svelte";

let extract: TypeaheadProps<{ id: number }>["extract"] = (item) => item;

@ChrRubin
Copy link
Author

Generic events and slots would be very useful when they are tied to generic-typed props.

Using svelte-virtual-scroll-list as an example for slots:

<script lang="ts">
  import VirtualScroll from 'svelte-virtual-scroll-list';

  let items = [{ id: 0, text: 'zero'}, { id: 1, text: 'one'}];
</script>

<VirtualScroll data={items} key="id" let:data>
  <div>{data.id}</div>
  <div>{data.text}<div>
</VirtualScroll>

Since sveld currently doesn't support generics, the typings for the data prop and slot prop would be any[] and any respectively, which is not ideal in a TypeScript environment (the slot prop is currently generated as any[] due to them sharing the same name, but that's a separate issue).

For events, generics can be used when the dispatched detail object is based on another generic-typed prop(s):

<script>
  import { createEventDispatcher } from "svelte";

  /**
   * @template T
   * @type {T[]}
   */
  export let items = [];

  /**
   * @event {T} bar
   */
  const dispatch = createEventDispatcher();

  function foo(i) {
    dispatch('bar', items[i])
  }
</script>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants