typescript - 在 v-for 指令中使用 :key 屬性時,TypeScript 預期會出現類型錯誤
嘗試使用鍵來維護 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>
答案#1
你很可能在你的 Workspace 介面成員中沒有使用你預期的類型。你可能想要使用基礎型別而不是它們的物件對應(注意小寫):
interface Workspace {
id: number;
name: string;
}
參考 TS 文件以了解日常類型:
類型名稱
String、Number和Boolean(以大寫字母開頭)是合法的,但指的是一些在你的程式碼中很少出現的特殊內建類型。總是使用string、number或boolean作為類型。
