使用TypeScript时,似乎无法将组件用作类型。
例如,不可能像这样键入存储来容纳组件实例:
import AnyComponent from "./AnyComponent"
const componentStore = writable<SvelteComponent>(null)
$componentStore = AnyComponent
最后一行将给出以下错误:
输入'typeof \
也许是我对组件的键入方式有所遗漏,但是我希望能够使用这种模式。
这是我在写此问题之前打开的StackOverflow帖子,其中@dummdidumm指示我打开此问题。 我希望没关系。
你好there
一件事是,我们在Svelte组件类的内部定义中缺少某些属性/方法。 另一件事是键入错误,应该是writable<typeof SvelteComponent>
,否则您引用的是该组件的实例,而不是类类型。
我遇到了类似的问题。
import type { SvelteComponent } from 'svelte';
import Comp from './Comp.svelte';
const comp: SvelteComponent = Comp; // Type 'typeof SvelteComponentDev' is missing the following properties from type SvelteComponentDev: $set, $on, $destroy ...
v 3.35.0
问题是,为什么导入的组件的类型为“ typeof SvelteComponentDev”而不是SvelteComponentDev
因为Comp
是类,而不是该类的实例。
class Foo {
bar: string;
}
class Comp extends Foo {}
const comp: Foo = new Comp(); // OK
const compClass1: Foo = Comp; // WRONG
const compClass2: typeof Foo = Comp; // OK
啊说得通。 谢谢你。
现在就与这个战斗了2天。 我只是不明白:
<script lang="ts">
import MyComponent from "./MyComponent.svelte";
let myComponent: typeof MyComponent;
</script>
<MyComponent bind:this={myComponent}/> //Error here
Argument of type 'typeof MyComponent__SvelteComponent_' is not assignable to parameter of type 'MyComponent__SvelteComponent_'.
Type 'typeof MyComponent__SvelteComponent_' is missing the following properties from type 'MyComponent__SvelteComponent_': $$prop_def, $$events_def, $$slot_def, $on, and 5 more.ts(2345)
我在这里做错了什么? 我只想将该实例放入变量中。 😭
@ Alfagun74您面临的问题与此线程中的其他问题不同。 您想要的是该类的一个实例。 因此,您只需要:
<script lang="ts">
import MyComponent from "./MyComponent.svelte";
let myComponent: MyComponent;
</script>
<MyComponent bind:this={myComponent}/>
其他人想要一个动态组件,因此他们需要类本身,一个特殊的功能。
最有用的评论
你好there
一件事是,我们在Svelte组件类的内部定义中缺少某些属性/方法。 另一件事是键入错误,应该是
writable<typeof SvelteComponent>
,否则您引用的是该组件的实例,而不是类类型。