【发布时间】:2021-10-29 13:05:55
【问题描述】:
我有 component1 将 let text 作为 props,然后 component2 做几乎相同的事情,但我想将 component1 分开以提高可重用性。
所以我用 comp2 (Wrapper.svelte) 包裹了 comp1 (Child.svelte)。但是如何在不重新编写的情况下保持 Child 组件的默认 prop 值呢?
这是一个例子:
//Wrapper.svelte
<script lang="ts">
import Child from "./Child.svelte";
export let text = 'hello world'; //need to type the default value again
</script>
<Child text={text} />
//Child.svelte
<script lang="ts">
export let text = 'hello world';
</script>
<p>{text}</p>
【问题讨论】:
-
如果你只是在 Wrapper.svelte 中的
export let text;需要这个,它将是未定义的,并在 Child 中使用默认值。 -
因为如果 text prop 没有默认值并且我没有从外部分配那个 prop,就会出现 typescript 错误:
Type '{}' is not assignable to type 'IntrinsicAttributes & { text: string;}'. Property 'text' is missing in type '{}' but required in type '{ text: string; }'.ts(2322) -
在这种情况下,将类型定义为“字符串或未定义”
标签: javascript typescript svelte svelte-component