Vue3中TypeScript类型

1,032 阅读6分钟

前言

阅读此文之前希望大家能先去官方文档简单的看一下TypeScript。选择适合自己的IDE,官方强烈推荐VS Code,因为它对 TypeScript推导有着很好的内置支持,Vue - Official (之前是 Volar) 是官方的 VS Code 扩展

相信学过JAVA的同学看这个TS的写法一定不会陌生,因为它跟Java的写法非常类似。

基于目前的市场以及技术,相信各位前端小伙伴的都知道TS的重要性以及他在前端的地位,不得不说,TS必须是每一位前端同学必学,接下来简单写一下Vue3中组件数据类型的标注

为组件的props标注类型

使用 <script setup>时,defineProps() 宏函数支持从它的参数中推导类型

// 子组件数据接收
<script setup lang="ts">
const props = defineProps({
  name: { type: String, required: true }, //type:数据的类型 required:是否为必须项(如果声明了,没有传,则会报错)
  age: Number
})
</script>

通过泛型参数来定义 props 的类型

<script setup lang="ts">
const props = defineProps<{
  name: string
  age?: number
}>()
</script>

这被称之为基于类型的声明,编译器会尽可能地尝试根据类型参数推导出等价的运行时选项

通过接口定义props的类型

我们也可以将 props 的类型移入一个单独的接口中,这样适用于模块化开发,我们可以将类型的定义放在单独的文件当中

<script setup lang="ts">
interface Props {
  name: string
  age?: number
}

const props = defineProps<Props>()
</script>
// data.ts
<script setup lang="ts">
import type { Props } from './data'

const props = defineProps<Props>()
</script>

Props 解构默认值

使用基于类型的声明时,我们失去了为 props 声明默认值的能力。这可以通过 withDefaults 编译器宏解决

export interface Props {
  name?: string
  array?: string[]
}

const props = withDefaults(defineProps<Props>(), {
  name: '孙悟空',
  array: () => ['one', 'two']
})

非 <script setup> 场景下

如果没有使用 <script setup>,那么为了开启 props 的类型推导,必须使用 defineComponent()。传入 setup() 的 props 对象类型是从 props 选项中推导而来。

import { defineComponent } from 'vue'

export default defineComponent({
  props: {
    message: String
  },
  setup(props) {
    props.message // <-- 类型:string
  }
})

复杂的 prop 类型

通过基于类型的声明,一个 prop 可以像使用其他任何类型一样使用一个复杂类型

<script setup lang="ts">
interface Book {
  title: string
  author: string
  year: number
}

const props = defineProps<{
  book: Book
}>()
</script>

对于运行时声明,我们可以使用 PropType 工具类型:

import type { PropType } from 'vue'

const props = defineProps({
  book: Object as PropType<Book>
})

其工作方式与直接指定 props 选项基本相同:
import { defineComponent } from 'vue';
import type { PropType } from 'vue';

export default defineComponent({
  props: {
    book: Object as PropType<Book>
  }
})

为组件的 emits 标注类型

<script setup> 中,emit 函数的类型标注也可以通过运行时声明或是类型声明进行

<script setup lang="ts">
// 运行时
const emit = defineEmits(['change', 'update'])

// 基于选项
const emit = defineEmits({
  change: (id: number) => {
    // 返回 `true` 或 `false`
    // 表明验证通过或失败
  },
  update: (value: string) => {
    // 返回 `true` 或 `false`
    // 表明验证通过或失败
  }
})

// 基于类型
const emit = defineEmits<{
  (e: 'change', id: number): void
  (e: 'update', value: string): void
}>()

// 3.3+: 可选的、更简洁的语法
const emit = defineEmits<{
  change: [id: number]
  update: [value: string]
}>()
</script>

类型参数可以是以下的一种:

一个可调用的函数类型,但是写作一个包含调用签名的类型字面量。它将被用作返回的 emit 函数的类型。

一个类型字面量,其中键是事件名称,值是数组或元组类型,表示事件的附加接受参数。上面的示例使用了具名元组,因此每个参数都可以有一个显式的名称。

我们可以看到,基于类型的声明使我们可以对所触发事件的类型进行更细粒度的控制。

若没有使用 <script setup>defineComponent() 也可以根据 emits 选项推导暴露在 setup 上下文中的 emit 函数的类型

import { defineComponent } from 'vue'

export default defineComponent({
  emits: ['change'],
  setup(props, { emit }) {
    emit('change') // <-- 类型检查 / 自动补全
  }
})

为 ref() 标注类型

ref 会根据初始化时的值推导其类型

import { ref } from 'vue'

// 推导出的类型:Ref<number>
const year = ref(2020)

// => TS Error: Type 'string' is not assignable to type 'number'.
year.value = '2020'

有时我们可能想为 ref 内的值指定一个更复杂的类型,可以通过使用 Ref 这个类型; 或者, 在调用 ref() 时传入一个泛型参数,来覆盖默认的推导行为

import { ref } from 'vue'
import type { Ref } from 'vue'

const year: Ref<string | number> = ref('2020')

year.value = 2020 // 成功!


// 传入泛型参数覆盖默认推导行为得到的类型:Ref<string | number>
const year = ref<string | number>('2020')

year.value = 2020 // 成功!

如果你指定了一个泛型参数但没有给出初始值,那么最后得到的就将是一个包含 undefined 的联合类型

// 推导得到的类型:Ref<number | undefined>
const n = ref<number>()

为 reactive() 标注类型

reactive() 也会隐式地从它的参数中推导类型

import { reactive } from 'vue'

// 推导得到的类型:{ title: string }
const book = reactive({ title: 'Vue 3 指引' })

要显式地标注一个 reactive 变量的类型,我们可以使用接口

import { reactive } from 'vue'

interface Book {
  title: string
  year?: number
}

const book: Book = reactive({ title: 'Vue 3 指引' })

为 computed() 标注类型

computed() 会自动从其计算函数的返回值上推导出类型

import { ref, computed } from 'vue'

const count = ref(0)

// 推导得到的类型:ComputedRef<number>
const double = computed(() => count.value * 2)

// => TS Error: Property 'split' does not exist on type 'number'
const result = double.value.split('')

你还可以通过泛型参数显式指定类型

const double = computed<number>(() => {
  // 若返回值不是 number 类型则会报错
})

为事件处理函数标注类型

在处理原生 DOM 事件时,应该为我们传递给事件处理函数的参数正确地标注类型。

<script setup lang="ts">
function handleChange(event) {
  // `event` 隐式地标注为 `any` 类型
  console.log(event.target.value)
}
</script>

<template>
  <input type="text" @change="handleChange" />
</template>

//建议手动标注类型
function handleChange(event: Event) {
  console.log((event.target as HTMLInputElement).value)
}

为 provide / inject 标注类型

provide 和 inject 通常会在不同的组件中运行。要正确地为注入的值标记类型,Vue 提供了一个 InjectionKey 接口,它是一个继承自 Symbol 的泛型类型,可以用来在提供者和消费者之间同步注入值的类型:

import { provide, inject } from 'vue'
import type { InjectionKey } from 'vue'

const key = Symbol() as InjectionKey<string>

provide(key, 'foo') // 若提供的是非字符串值会导致错误

const foo = inject(key) // foo 的类型:string | undefined

为模板引用标注类型

模板引用需要通过一个显式指定的泛型参数和一个初始值 null 来创建

注意为了严格的类型安全,有必要在访问 el.value 时使用可选链或类型守卫。这是因为直到组件被挂载前,这个 ref 的值都是初始的 null,并且在由于 v-if 的行为将引用的元素卸载时也可以被设置为 null。

<script setup lang="ts">
import { ref, onMounted } from 'vue'

const el = ref<HTMLInputElement | null>(null)

onMounted(() => {
  el.value?.focus()
})
</script>

<template>
  <input ref="el" />
</template>

为组件模板引用标注类型

有时,你可能需要为一个子组件添加一个模板引用,以便调用它公开的方法。举例来说,我们有一个 MyModal 子组件,它有一个打开模态框的方法:

<!-- MyModal.vue -->
<script setup lang="ts">
import { ref } from 'vue'

const isContentShown = ref(false)
const open = () => (isContentShown.value = true)

defineExpose({
  open
})
</script>

为了获取 MyModal 的类型,我们首先需要通过 typeof 得到其类型,再使用 TypeScript 内置的 InstanceType 工具类型来获取其实例类型:

<!-- App.vue -->
<script setup lang="ts">
import MyModal from './MyModal.vue'

const modal = ref<InstanceType<typeof MyModal> | null>(null)

const openModal = () => {
  modal.value?.open()
}
</script>

如果组件的具体类型无法获得,或者你并不关心组件的具体类型,那么可以使用 ComponentPublicInstance。这只会包含所有组件都共享的属性,比如 $el。

import { ref } from 'vue'
import type { ComponentPublicInstance } from 'vue'

const child = ref<ComponentPublicInstance | null>(null)