Home > Blockchain >  How to type a function that receives a Svelte component
How to type a function that receives a Svelte component

Time:01-06

I have a component with a prop that is an async function that should a Svelte Component

liek this

// MyComponent.svelte
<script lang="ts">
    export let icon: () => Promise<any>;
</script>

// do some stuff with icon...

And I'd like to type that parameter, instead of using any.

I tried with the following:

<script lang="ts">
    import type { ComponentType } from 'svelte';
    export let icon: () => Promise<Component>;
</script>

But when calling it like this:

<MyComponent icon={() => import('./Logo.svelte')}>

I get the following error:

Error: Type 'Promise<typeof import("./Logo.svelte")>' is not assignable to type 'Promise<ComponentType<SvelteComponentTyped<any, any, any>>>'.

Type 'typeof import("./Logo.svelte")' is not assignable to type 'ComponentType<SvelteComponentTyped<any, any, any>>'.

Type 'typeof import("./Logo.svelte")' provides no match for the signature 'new (options: ComponentConstructorOptions<any>): SvelteComponentTyped<any, any, any>'. (ts)

Also tried with export let icon: () => Promise<typeof SvelteComponent>; as stated here and I the this error:

Error: Type 'Promise<typeof import("./Logo.svelte")>' is not assignable to type 'Promise<typeof SvelteComponentDev>'.

Property 'prototype' is missing in type 'typeof import("./Logo.svelte")' but required in type 'typeof SvelteComponentDev'. (ts)

Any idea how to achieve it?

Note: I've been following this article: https://www.viget.com/articles/typing-components-in-svelte/

CodePudding user response:

() => Promise<ComponentType> is correct if you account for the fact that the dynamic import returns a module.

Either adjust the usage to:

import('./Logo.svelte').then(m => m.default)

Or change the type to () => Promise<{ default: ComponentType }> and extract the default export within the component.

  • Related