最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

typescript - Is there a type for the $props() of a component? - Stack Overflow

programmeradmin3浏览0评论

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({}) ?

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({}) ?

Share Improve this question asked Jan 20 at 11:25 CorrlCorrl 7,6991 gold badge17 silver badges45 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 2

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';
发布评论

评论列表(0)

  1. 暂无评论