Skip to content

Svelte 5 Generic component with JSDoc #2618

@falco467

Description

@falco467

Describe the problem

Hi,
we are working i a strictly typed JS + JSDoc environment. It is great that we can write type-safe props with @type and have full type-checking everywhere. We can also use generic functions and types with JSDoc @template {...} T
But it seems that using a generic Svelte component generics="T extends" is only possible with TypeScript.

We have a generic table component and it would be great if we could automatic type-safety in our snippets for the columns if we define the component with a generic row type, which would then be inferred by the passed array-type.

If I declare Props dynamic with JSDoc @template T ... I will always get type-errors when using the component, since the component will be instantiated as the concrete type Comp<Prop<T>> and not as a generic Type for which types can be inferred.

The workaround which I found is to explicitly type cast the component to the correct concrete type:

import Select from './Select.svelte'
const SelectNumber = /** @type {import('svelte').Component<import('./Select.svelte').Props<number>,{},"value">} */ (Select)

This works, but is quite cumbersome, since I have to create this cast anytime I want to use the component without errors.

It would be great if Svelte could support type inference by use, like normal generic types and functions do.

Here is a Playground sample with the working work around:
https://svelte.dev/playground/48be5dc1b4c040a8a98f5af6fa1291aa?version=5.2.7

Describe the proposed solution

First Solution would be to extend the generics=""... attribute to also support JavaScript & JSDoc instead of only Typescript.

Second Solution would be to automatically generate Components with generic Props as a generic Function with the same Type parameters - so the type-system could automatically infer the used types.

Third Solution would be to provide a way to explicitly provide Type-Parameters to components like <MyComponent[string, number] or maybe <MyComponent @types={...} or similar

Importance

would make my life easier

Metadata

Metadata

Assignees

No one assigned

    Labels

    FixedFixed in master branch. Pending production release.feature requestNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions