Home > Enterprise >  How can I type a component export?
How can I type a component export?

Time:12-01

I have the following component, where I have items a list of constructors for Svelte components:

<script lang="ts">
  // ...other script data
  export let items: ConstructorOfATypedSvelteComponent[];
</script>

<!-- ...some other html code -->
{#each items as item}
   <!-- ...even more html code -->
   <svelte:component this={item}></svelte:component>
{/each}

This is a barebones example, but as seen, it would be extremely inconvenient to use another feature such as named slots, so I stuck with using ConstructorOfATypedSvelteComponent.

However, in ConstructorOfATypedSvelteComponent's JSDocs:

/**
 * Ambient type only used for intellisense, DO NOT USE IN YOUR PROJECT
 */
declare type ConstructorOfATypedSvelteComponent = new (args: {target: any, props?: any}) => ATypedSvelteComponent

I am a bit confused by this warning -- what does SvelteJS want me to use for typing a component, or is there another way that I should approach this entirely?

CodePudding user response:

Would use this:

<script lang="ts">
    import type { ComponentType, SvelteComponentTyped } from 'svelte';

    export let items: ComponentType<SvelteComponentTyped>[];
</script>

The warning is there because your local build tools will not have access to that type definition as it merely exists to support editing. Hence you should use types that are directly exported from the svelte package instead.

You could also declare your own version of ConstructorOfATypedSvelteComponent but that seems rather unnecessary.

  • Related