使用:v-for指令中的键属性时TS的预期类型错误

发布于 2025-02-08 13:29:24 字数 1210 浏览 0 评论 0 原文

尝试用键保持状态代码> v-for 指令,但Typescript在上抛出以下错误:key 属性。

TS错误

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

代码

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

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>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

盗心人 2025-02-15 13:29:24

您可能没有在 workspace 接口成员中使用意图的类型。您可能需要原语,而不是其对象对应物(请注意小写):

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

参考日常类型

类型名称字符串号码 boolean (从大写字母开始)是合法的,但请参阅某些特殊的内置很少会出现在您的代码中的类型。 始终使用字符串号码,或 boolean 类型。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文