尝试使用v-for
指令的键来维护状态,但typescript在:key
属性上抛出以下错误:
(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文档中的日常类型:
类型名
String
、Number
和Boolean
(以大写字母开头)是合法的,但是指的是一些在代码中很少出现的特殊内置类型。总是使用string
、number
或boolean
作为类型。