SSF0SSF0
首页
前端
  • Node
  • Go
  • C#
  • MySql
  • Bash
  • Git
  • Docker
  • VuePress
  • CI/CD
  • 服务器
  • 网站
  • 学习资料
  • 软件
Timeline
Github
标签
分类
首页
前端
  • Node
  • Go
  • C#
  • MySql
  • Bash
  • Git
  • Docker
  • VuePress
  • CI/CD
  • 服务器
  • 网站
  • 学习资料
  • 软件
Timeline
Github
标签
分类
  • HTML

    • html1
    • html2
  • CSS

    • Flex 布局常见问题与解决方案
  • JavaScript

    • 数据类型及引用问题
    • 处理 Blob 类型文件下载问题总结
    • localStorage 与 sessionStorage 区别
    • JavaScript 中的 script 标签问题详解
    • JavaScript 中的`this`指向问题详解
    • SessionStorage踩坑记录:它真的能"只设置一次"吗?
    • 动态加载 JS 脚本方法对比
    • 浏览器页面关闭场景下的数据上报
  • es6

    • Promise
    • es6 模块导出方式全解析
  • Vue2

    • created VS mounted 发起异步请求
    • vue2-2
  • Vue3

    • Vite + Vue3 修改 element-plus 源码
    • Vue v-if 与 v-show
    • Vue3 ref 获取组件
    • Vue3 路由传参
    • 父子组件与组件里 Hooks 加载顺序
    • 第三方组件传入参数TS提示
    • Vue3 Props 在 Hooks 中的响应性处理
    • Vue Router 的两种历史模式及部署配置详解
    • 在Vue 3项目中顺利集成Tailwind CSS的完整指南
    • Vue 3 深度选择器:deep()完全指南
  • Electron

    • 快速构建 electron + vue3 项目
  • TS

    • TS 泛型
    • 记录模板使用断言的问题
    • type 与 interface
  • WebPack

    • Webpack 介绍
  • Vite

    • Vite CLI 常见命令
    • vite 与 webpack 比较
  • 项目工程

    • 前端代码风格
    • Vue3 项目规范
    • npm 镜像问题
    • 包管理工具
    • 使用 engines 限制开发环境依赖
    • 打包与shell交互指定模式
    • 使用 pnpm 构建 Monorepo 实战指南
    • pnpm 修改依赖源码打包报错
  • 记录一下小程序
  • 控制浏览器正确保存网站账号密码的技巧

记录模板里面使用断言的问题

断言报错

<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 }[] 类型。
最后更新时间:
贡献者: 何风顺
上一页
TS 泛型
下一页
type 与 interface