Home > Enterprise >  Expected type error from TS when using the :key attribute within v-for directive
Expected type error from TS when using the :key attribute within v-for directive

Time:06-19

Attempting to maintain state with a key for a v-for directive but typescript throws the following error on the :key attribute.

TS Error

(property) key?: string | number | symbol
Type '{ toString: (radix?: number) => string; toFixed: (fractionDigits?: number) => string; toExponential: (fractionDigits?: number) => string; toPrecision: (precision?: number) => string; valueOf: () => number; toLocaleString: { ...; }; }' is not assignable to type 'string | number | symbol'.ts(2322)
runtime-dom.d.ts(1480, 3): The expected type comes from property 'key' which is declared here on type 'ElementAttrs<LiHTMLAttributes>'

Code

<script lang="ts" setup>
  import { ref } from 'vue';

  interface Workspace {
    id: Number
    name: String
  }

  const workspaceList = ref<Workspace[]>([])
</script>

<template>
  <div>
    <ul>
      <li v-for="workspace in workspaceList" :key="workspace.id">
        {{ workspace.id }}: {{ workspace.name }}
      </li>
    </ul>
  </div>
</template>

CodePudding user response:

It's likely that you are not using the types that you intended in your Workspace interface members. You probably want primitives rather than their object counterparts (note the lowercase):

interface Workspace {
  id: number;
  name: string;
}

Reference the TS documentation for everyday types:

The type names String, Number, and Boolean (starting with capital letters) are legal, but refer to some special built-in types that will very rarely appear in your code. Always use string, number, or boolean for types.

  • Related