Language-tools: [TypeScript]コンポーネントを値として保持する変数を入力する

作成日 2020年08月26日  ·  6コメント  ·  ソース: sveltejs/language-tools

TypeScriptを使用する場合、コンポーネントをタイプとして使用することは不可能のようです。
たとえば、次のようにコンポーネントインスタンスを保持するストアを入力することはできません。

import AnyComponent from "./AnyComponent"

const componentStore = writable<SvelteComponent>(null)

$componentStore = AnyComponent

最後の行で次のエラーが発生します。

タイプ 'typeof \

コンポーネントの型付け方法について何か見落としているのは私かもしれませんが、そのようなパターンを使用できるようにしたいと思います。

これは、この問題を書く前に開いたStackOverflowの投稿で、 @ dummdidummがこの問題を開くように指示しました。 大丈夫だといいのですが。

Fixed bug

最も参考になるコメント

こんにちは😄
1つは、Svelteコンポーネントクラスの内部定義にいくつかのプロパティ/メソッドが欠落していることです。 もう1つは、入力が間違っていることです。 writable<typeof SvelteComponent>である必要があります。そうでない場合は、クラスタイプではなく、そのコンポーネントのインスタンスを参照しています。

全てのコメント6件

こんにちは😄
1つは、Svelteコンポーネントクラスの内部定義にいくつかのプロパティ/メソッドが欠落していることです。 もう1つは、入力が間違っていることです。 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

問題は、インポートされたコンポーネントのタイプがSvelteComponentDevではなく「typeofSvelteComponentDev」である理由です。

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)

私はここで何が間違っているのですか? そのインスタンスを変数に入れたいだけです。 😭

@ Alphagun74あなたが直面している問題は、このスレッドの他の問題と同じではありません。 必要なのはクラスのインスタンスです。 だからあなたはただ必要です:

<script lang="ts">
  import MyComponent from "./MyComponent.svelte";
  let myComponent: MyComponent;
</script>

<MyComponent bind:this={myComponent}/>

他の人々は動的コンポーネントを望んでいるので、クラス自体、特別な関数が必要です。

このページは役に立ちましたか?
0 / 5 - 0 評価