如何键入 cast Svelte 3 反应式语法变量?

How to type cast Svelte 3 reactive syntax variables?

我不知道如何输入 Svelte 3 响应式语法变量。

<script lang="ts">
  import type { Player, Team } from "./types";

  import { DEFAULT_PLAYER } from "./utils";

  $: player = DEFAULT_PLAYER as Player;
    $: team = { search: "Real", players: [] } as Team;
</script>

但这行不通:

'Team' cannot be used as a value because it was imported using 'import type'.ts(1361)

如果我改用这个:

$: team = ({ search: "Real", players: [] } as Team);

VSCode 扩展 svelte.svelte-vscode 保存时像第一个一样格式化。

这是我的错吗?

是否有更好的方法来转换那些反应性变量?

我认为你应该这样做

<script lang="ts">
  import type { Player, Team } from "./types";

  import { DEFAULT_PLAYER } from "./utils";

  let team: Team;  // added this
  $: player = DEFAULT_PLAYER as Player;
    $: team = { search: "Real", players: [] };
</script>
<script lang="ts">
  import type { Player, Team } from "./types";

  import { DEFAULT_PLAYER } from "./utils";

  let player: Player;
  $: player = DEFAULT_PLAYER;
  let team: Team;
  $: team = { search: "Real", players: [] };
</script>

我不喜欢使用 as 进行类型转换,我会尽可能避免使用它。使用 as 进行类型转换会导致运行时类型错误,因为您告诉编译器“这个变量将始终是这种类型,相信我”。

相反,首先使用类型声明声明您的反应变量。在上面的例子中……

<script lang='ts'>
  let team: Team;
  $: team = { search: "Real", players: [] }
</script>

…不需要类型转换!