|
I have the following setup: A <script lang="ts">
import type { SubmitFunction } from '@sveltejs/kit' // Where to put the type?
import { enhance } from '$app/forms'
let {
children,
actionUrl = '',
submitFunction = () => {
return async ({ update }) => {
await update()
}
},
} = $props()
</script>
<form method="post" action={actionUrl} use:enhance={submitFunction}>
{@render children()}
</form>Now I get the following TS error when passing the function to My question is how to type the (The |
Replies: 2 comments 2 replies
They cannot be inferred because this is the left side of an assignment, the only thing that can be inferred is the type of the default values, which do not necessarily have anything to do with the values provided by whatever is on the right side of the assignment. The resulting type of the variables will be an intersection of both. I do not know of any way to avoid typing everything, the only minor optimization would be adding a utility type for let { ... }: {
children: Snippet,
actionUrl?: string,
submitFunction?: SubmitFunction,
} = $props();let { ... }: HasChildren & {
actionUrl?: string,
submitFunction?: SubmitFunction,
} = $props();You can also extract a local type/interface for the props of the component; this is what the migration tool will do and what I would recommend. interface Props {
children: Snippet,
actionUrl?: string,
submitFunction?: SubmitFunction,
}
let { ... }: Props = $props();interface Props extends HasChildren {
actionUrl?: string,
submitFunction?: SubmitFunction,
}
let { ... }: Props = $props(); |
|
Hi @rgeditz , here is another example from the documentation: https://svelte.dev/docs/svelte/typescript#Generic-$props <script lang="ts" generics="Item extends { text: string }">
interface Props {
items: Item[];
select(item: Item): void;
}
let { items, select }: Props = $props();
</script>
{#each items as item}
<button onclick={() => select(item)}>
{item.text}
</button>
{/each} |
They cannot be inferred because this is the left side of an assignment, the only thing that can be inferred is the type of the default values, which do not necessarily have anything to do with the values provided by whatever is on the right side of the assignment.
The resulting type of the variables will be an intersection of both.
I do not know of any way to avoid typing everything, the only minor optimization would be adding a utility type for
{ children: Snippet }.