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



尝试使用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>

很可能你没有在Workspace接口成员中使用你想要的类型。您可能需要的是原语而不是对应的对象(注意小写):

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

参考TS文档中的日常类型:

类型名StringNumberBoolean(以大写字母开头)是合法的,但是指的是一些在代码中很少出现的特殊内置类型。总是使用stringnumberboolean作为类型。

最新更新