Having a component
// Comp.svelte
<script lang="ts">
interface Props {
value?: number;
}
let { value }:Props = $props()
</script>
that will be mounted in a *.svelte.ts
file
const props = $state({})
const comp = mount(Comp, {
target: '#target',
props: props,
}
props.value = 100 //error: Property 'value' does not exist on type {}
I wonder if there's an alternative way of typing the props state other than moving the interface out of the component?
Something like const props: ComponentProps<Comp> = $state({})
?
There is such a type, but it needs to be used with typeof
:
import { type ComponentProps } from 'svelte';
const props: ComponentProps<typeof Comp> = $state({});
The interface can also be exported directly from the component.
<script lang="ts">
export interface Props { ... }
// ...
</script>
import Comp, { type Props } from './Comp.svelte';