How to type cast Svelte 3 reactive syntax variables?

Viewed 1297

I don't know how to type Svelte 3 reactive syntax variables.

<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>

But this doesn't work:

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

If I use this instead:

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

the VSCode extension svelte.svelte-vscode format it like the first one when I save.

Is this my fault?

Is there a better way to cast those reactive vars?

2 Answers
<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>

I'm not a fan of using as to type cast and will avoid it at all possible. Type casting with as can lead to runtime type errors because you're telling the compiler "this variable will always be this type, trust me".

Instead, declare your reactive variable first with the type declaration. In the above case…

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

… no type casting needed!

I think you should do

<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>
Related