【问题标题】:How to type cast Svelte 3 reactive syntax variables?如何键入 cast Svelte 3 反应式语法变量?
【发布时间】:2021-07-03 23:25:45
【问题描述】:

我不知道如何键入 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 在我保存时将其格式化为第一个。

这是我的错吗?

有没有更好的方法来转换这些反应变量?

【问题讨论】:

    标签: typescript casting svelte svelte-3


    【解决方案1】:
    <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>
    

    …无需类型转换!

    【讨论】:

      【解决方案2】:

      我认为你应该这样做

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-12-05
        • 2020-03-28
        • 2023-02-22
        • 2022-11-02
        • 2021-02-08
        • 2016-08-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多