记录模板里面使用断言的问题
断言报错
<template>
<template v-if="Array.isArray(ces)">
<img v-for="item in (ces as ImageItem[])" :src="item.img_url" alt="" />
<img
v-for="item in (ces as Array<{ img_url: string }>)"
:src="item.img_url"
alt=""
/>
<img v-for="item in ces" :src="item.img_url" alt="" />
<img
v-for="item in (ces as { img_url: string }[])"
:src="item.img_url"
alt=""
/>
<img
v-for="item in (<{ img_url: string }[]>ces)"
:src="item.img_url"
alt=""
/>
</template>
<template v-else>
<img :src="ces" alt="" />
</template>
</template>
<script setup lang="ts">
import { Ref } from "vue";
import { ref } from "vue";
const ces: Ref<string | { img_url: string }[]> = ref("ces");
interface ImageItem {
img_url: string;
}
</script>
<style lang="scss" scoped></style>
问题

这时候发现,
ces as { img_url: string }[]
,<{ img_url: string }[]>ces
这两种写法,在模板里面是会报错的。但是
ces as ImageItem[]
和ces as Array<ImageItem>
这两种写法,在模板里面是正常的。
说明
也是找了很久,没找到相关的资料,所以记录一下。
自我猜测:
- 在模板里面的使用的类型要是一个整体,比如
ImageItem[]
,Array<ImageItem>
,不能是{ img_url: string }[]
,这种应该是通过特殊编译。
- 在模板里面的使用的类型要是一个整体,比如
ref 变量
这时候,初始值虽然给的是 string
,但是 ces
的类型是 Ref<string | { img_url: string }[]>
,而且在模板里面,ces
的类型是 (property) ces: {img_url: string;}[]
。

普通变量
这时候,里面的 ces
就是 string
类型。

原因
- 因为初始值是
string
,所以ces
就是string
类型,如果初始值是[{ img_url: "ces" }]
,那么ces
就是{ img_url: string }[]
类型。