[Vuejs]-Typescript Vue, keyof Ref object

0👍

You are mixing types and values.

const activePlayerId = ref<keyof Players>(1); // Would only return the type of the player, which is always Player

Rewrite as follows:

const players = ref([
  {
    id: 1,
    name: "Player 1",
    questionIds: [],
    modifierIds: [],
  },
  {
    id: 2,
    name: "Player 2",
    questionIds: [],
    modifierIds: [],
  },
]);

const activePlayerId = ref(1);

If you track the id of the active player separately, the code is simpler and more maintainable. You would get the active player this way:

const activePlayer = computed(() => players.value.find((player) => player.id === activePlayerId.value));

If you are certain that there is always one player selected, you can type the following to tell TypeScript that it cannot be undefined:

computed(() => players.value.find(...) as Player)

Leave a comment