Skip to content

组合式 API 中 TS 写法

props

声明 props

ts
const props = defineProps({
  foo: { type: String, required: true },
  bar: Number,
})
ts
interface Props {
  foo: string
  bar?: number
}

const props = defineProps<Props>()

注意

“运行时声明”和“基于类型的声明”可以择一使用,但是不能同时使用。

语法限制

3.2 及以下版本中,defineProps() 的泛型类型参数仅限于类型字面量或对本地接口的引用。

这个限制在 3.3 中得到了解决。

最新版本的 Vue 支持在类型参数位置引用导入和有限的复杂类型。但是,由于类型到运行时转换仍然基于 AST,一些需要实际类型分析的复杂类型,例如条件类型,还未支持。你可以使用条件类型来指定单个 prop 的类型,但不能用于整个 props 对象的类型。

声明 props 默认值

ts
interface Props {
  msg?: string
  labels?: string[]
}

const { msg = 'hello', labels = ['one', 'two'] } = defineProps<Props>()
ts
interface Props {
  msg?: string
  labels?: string[]
}

const props = withDefaults(defineProps<Props>(), {
  msg: 'hello',
  labels: () => ['one', 'two'],
})

提示

  • 在使用 withDefaults 时,默认值的可变引用类型 (如数组或对象) 应该在函数中进行包装,以避免意外修改和外部副作用。这样可以确保每个组件实例都会获得自己默认值的副本。
  • 在使用解构时,这不是必要的。

emits

ts
const emit = defineEmits(['change', 'update'])
ts
const emit = defineEmits({
  change: (id: number) => {
    // 返回 `true` 或 `false`
    // 表明验证通过或失败
  },
  update: (value: string) => {
    // 返回 `true` 或 `false`
    // 表明验证通过或失败
  },
})
ts
const emit = defineEmits<{
  (e: 'change', id: number): void
  (e: 'update', value: string): void
}>()
ts
const emit = defineEmits<{
  change: [id: number]
  update: [value: string]
}>()

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

  • 一个可调用的函数类型,但是写作一个包含调用签名的类型字面量。它将被用作返回的 emit 函数的类型。
  • 一个类型字面量,其中键是事件名称,值是数组或元组类型,表示事件的附加接受参数。上面的示例使用了具名元组,因此每个参数都可以有一个显式的名称。

ref()

ts
// 推导出的类型:Ref<number>
const year = ref(2020)
ts
import type { Ref } from 'vue'

const year: Ref<string | number> = ref('2020')
ts
// 得到的类型:Ref<string | number>
const year = ref<string | number>('2020')

// 如果指定了一个泛型参数但没有给出初始值,那么最后得到的就将是一个包含 undefined 的联合类型:
// 推导得到的类型:Ref<number | undefined>
const n = ref<number>()

reactive()

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

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

为什么不推荐使用泛型?

不推荐使用 reactive() 的泛型参数,是因为处理了深层次 ref 解包的返回值与泛型参数的类型不同。

computed()

ts
const count = ref(0)
// 推导得到的类型:ComputedRef<number>
const double = computed(() => count.value * 2)
ts
const double = computed<number>(() => {
  // 若返回值不是 number 类型则会报错
})

事件处理函数

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

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

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

没有类型标注时,这个 event 参数会隐式地标注为 any 类型。这也会在 tsconfig.json 中配置了 "strict": true"noImplicitAny": true 时报出一个 TS 错误。

因此,建议显式地为事件处理函数的参数标注类型。此外,你在访问 event 上的属性时可能需要使用类型断言:

ts
// ✅ `event` 明确地标注为 `Event` 类型
function handleChange(event: Event) {
  console.log((event.target as HTMLInputElement).value)
}

provide/inject

提示

InjectionKey 接口,它是一个继承自 Symbol 的泛型类型。

inject 类型定义:

ts
import type { InjectionKey } from 'vue'

const key = Symbol() as InjectionKey<string>

// 类型:string | undefined
const foo = inject(key)
ts
const foo = inject<string>('foo') // 类型:string | undefined

// 当提供了一个默认值后,这个 undefined 类型就可以被移除:
const foo = inject<string>('foo', 'bar') // 类型:string

// 如果确定该值将始终被提供,则还可以强制转换该值:
const foo = inject('foo') as string

provide 使用示例:

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

模板引用

Vue 3.5 以前:

vue
<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>

Vue 3.5@vue/language-tools 2.1 (为 IDE 语言服务和 vue-tsc 提供支持) 中,在单文件组件中由 useTemplateRef() 创建的 ref 类型可以基于匹配的 ref attribute 所在的元素 自动推断 为静态类型。

ts
const el = useTemplateRef('el')

在无法自动推断的情况下,仍然可以通过泛型参数将模板 ref 转换为显式类型。

ts
const el = useTemplateRef<HTMLInputElement>('el')

组件模板引用

Vue 3.5@vue/language-tools 2.1 (为 IDE 语言服务和 vue-tsc 提供支持) 中,在单文件组件中由 useTemplateRef() 创建的 ref 类型可以基于匹配的 ref attribute 所在的元素 自动推断 为静态类型。

vue
<script setup lang="ts">
import { useTemplateRef } from 'vue'
import Foo from './Foo.vue'

const compRef = useTemplateRef('comp')
</script>

<template>
  <Foo ref="comp" />
</template>

在无法自动推断的情况下 (如非单文件组件使用或动态组件),仍然可以通过泛型参数将模板 ref 强制转换为显式类型。

vue
<script setup lang="ts">
import { useTemplateRef } from 'vue'
import Foo from './Foo.vue'
import Bar from './Bar.vue'

type FooType = InstanceType<typeof Foo>
type BarType = InstanceType<typeof Bar>

const compRef = useTemplateRef<FooType | BarType>('comp')
</script>

<template>
  <component :is="Math.random() > 0.5 ? Foo : Bar" ref="comp" />
</template>

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

ts
import { useTemplateRef } from 'vue'
import type { ComponentPublicInstance } from 'vue'

const child = useTemplateRef<ComponentPublicInstance>('child')

如果引用的组件是一个泛型组件,则需要使用 vue-component-type-helpers 库中的 ComponentExposed 来引用组件类型,因为 InstanceType 在这种场景下不起作用。

vue
<script setup lang="ts" generic="ContentType extends string | number">
import { ref } from 'vue'

const content = ref<ContentType | null>(null)

const open = (newContent: ContentType) => (content.value = newContent)

defineExpose({
  open,
})
</script>
vue
<script setup lang="ts">
import { useTemplateRef } from 'vue'
import MyGenericModal from './MyGenericModal.vue'
import type { ComponentExposed } from 'vue-component-type-helpers'

const modal = useTemplateRef<ComponentExposed<typeof MyGenericModal>>('modal')

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

请注意在 @vue/language-tools 2.1 以上版本中,静态模板 ref 的类型可以被自动推导,上述这些仅在极端情况下需要。

基于 MIT 许可发布