首页 > 解决方案 > Svelte 3,如果我使用响应式语句,为什么不能访问这个 javascript 对象属性?

问题描述

我将此代码与 Svelte 3 一起使用:

REPL:https ://svelte.dev/repl/bf73fffc1b9442dfbcd492eaa9c048e1?version=3.35.0

<script lang="ts">
  const players = {
    men: {
      john: "high",
      bob: "low",
    },
  };

  // const player = "bob"
  $: player = "bob";

  const test = players.men[player];

  console.log(test); //prints undefined
</script>

{player} //bob
{test} //undefined

打字稿甚至告诉我:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ john: string; bob: string; }'.
  No index signature with a parameter of type 'string' was found on type '{ john: string; bob: string; }'.ts(7053)

如果我使用const player = "bob" 它就可以了!

为什么?

标签: typescriptsveltesvelte-3

解决方案


您不能使用随机字符串安全地访问对象,这就是编译器抱怨的原因。使用时它不会抱怨的原因const是常量字符串文字在编译时已知,并且在运行时无法更改,因此编译器知道它是安全的。有几种方法可以解决这个问题,但最简单(NB 不是最安全)的方法是强制转换:

  const players = {
    men: {
      john: "high",
      bob: "low",
    },
  };

  // const player = "bob"
  let player = "bob";

  const test = players.men[player as keyof typeof players.men];

可能还存在一种更安全的方法来使用您尝试使用的 Svelte 东西来执行此操作,通常在 TS 中编写此类内容时,我将使用字符串文字或枚举让编译器确保我没有得到意外undefined

enum Males {
  JOHN = "john",
  BOB = "bob"
}

const players: {
  men: {
    [key in Males]: string;
  }
} = {
  men: {
    john: "high",
    bob: "low",
  },
};

const test2 = players.men[Males.JOHN];

操场


推荐阅读