英文:
How to correctly infer Svelte props type?
问题
Option 1: Type-cast the $$props
<script lang="ts">
    interface ComponentPropType {
        a: string;
        b: number;
    }
    export let { a, b } = $$props as ComponentPropType;
</script>
<h1>a = {a} </h1>
<p>My value is {b} </p>
Option 2: De-structure the props specified by export let
<script lang="ts">
    interface ComponentPropType {
        a: string;
        b: number;
    }
    export let props: ComponentPropType;
    export let { a, b } = props;
</script>
<h1>a = {a} </h1>
<p>My value is {b} </p>
If we use Option 1 - we can render the component as <MyComponent {{a, b}} /> or <MyComponent {a} {b} />.
On the other hand, if we use Option 2 - we need to render the component as <MyComponent props={{a, b}} />. In this case, we can't use the prop-spread.
Which one is the correct way to do it? Is there a better solution?
英文:
I have a svelte component (SvelteKit Project) - let's call it MyComponent. It accepts two props.
What would be the correct way to do it with TypeScript?
Option 1: Type-cast the $$props
<script lang="ts">
    interface ComponentPropType {
        a: string;
        b: number;
    }
	export let { a, b } = $$props as ComponentPropType;
</script>
<h1>a = {a} </h1>
<p>My value is {b} </p>
Or should I go with a bit verbose
Option 2: De-structure the props specified by export let
<script lang="ts">
    interface ComponentPropType {
        a: string;
        b: number;
    }
    export let props: ComponentPropType;
	export let { a, b } = props;
</script>
<h1>a = {a} </h1>
<p>My value is {b} </p>
If we use Option 1 -  we can render the component as <MyComponent {{a, b}} /> or <MyComponent {a} {b} />
Does this one prevent event forwarding (if any)?
On the other hand, if we use Option 2 - we need to render the component as <MyComponent props={{a, b}} />.
In this case, we can't use the prop-spread.
Which one is the correct way to do it? Is there a better solution?
答案1
得分: 2
我不认为那是必要的,但我并不完全确定你想要实现什么。
**应该**足够的是只需用`export let`定义props
```html
<script lang="ts">
    export let a: string
    export let b: number;
</script>
<h1>a = {a} </h1>
<p>我的值是 {b} </p>
然后你可以使用直接赋值
<Component a={"a"} b={2} />
或者扩展
<Component {...{a:"a", b:2}} />
请注意需要使用扩展运算符,因为{{a,b}}和{...{a,b}}不是相同的。
英文:
I don't think that's necessary, but I'm not 100% sure what you are trying to achieve.
What should be sufficient is to just define the props with export let
<script lang="ts">
    export let a: string
    export let b: number;
</script>
<h1>a = {a} </h1>
<p>My value is {b} </p>
This will then be enough for you to use either direct assignment
<Component a={"a"} b={2} />
or spread
<Component {...{a:"a", b:2}} />
Note that the spread operator needs to be used, as {{a,b}} is not the same as {...{a,b}}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论