直接参考Vue官方文档。
https://cn.vuejs.org/guide/typescript/overview.html#overview
一、TS与组合式API
1.为组件的 props 标注类型
2.为组件的 emits 标注类型
3.为 ref() 标注类型
4.为 reactive() 标注类型
5.为 computed() 标注类型
6.为事件处理函数标注类型
7.为 provide / inject 标注类型
8.为模板引用标注类型
9.为组件模板引用标注类型
二、TS与选项式AIP
1.为组件的 props 标注类型
(1)选项式 API 中对 props 的类型推导需要用 来包装组件。有了它,Vue 才可以通过 props 以及一些额外的选项,比如 required: true 和 default 来推导出 props 的类型:
import { defineComponent } from 'vue'
export default defineComponent({
// 启用了类型推导
props: {
name: String,
id: [Number, String],
msg: { type: Array, required: true, default: ()=>[] },
},
setup(props, { slots, attrs, expose, emit }) {}
}
(2)使用 这个工具类型来标记更复杂的 props 类型,如 多层级对象 或 函数签名:
import { defineComponent } from 'vue'
import type { PropType } from 'vue'
interface Book {
title: string
author: string
year: number
}
export default defineComponent({
props: {
book: {
// 提供相对 `Object` 更确定的类型
type: Object as PropType<Book>,
required: true
},
// 也可以标记函数
callback: Function as PropType<(id: number) => void>
},
setup(props, { slots, attrs, expose, emit }) {}
})