Skip to content

Vue3 中的 TS 类型声明总结

1. 响应式数据类型

ts
const str = ref<string>('hello world')
const str1 = ref<string[]>(['hello', 'world'])

const num = ref<number>(0)
const num1 = ref<number[]>([1, 2, 3])

const bool = ref<boolean>(false)
const bool = ref<boolean[]>([false, true])

const obj = ref<{ name: string; age: number }>({ name: 'Tom', age: 18 })
// 如果里面的属性较多,可先定义一个接口,如下:
interface IUser {
  name: string
  age: number
}
const user = ref<IUser>({ name: 'Tom', age: 18 })
// 在这个基础之上继续扩展
const userList = ref<IUser[]>([])

2. defineProps 中类型声明

ts
interface IProps {
  name: string
  age: number
  gender: string
}
const props = defineProps<IProps>()
// 像上面这样写会有一个问题,就是如何添加默认值呢? 用 withDefaults
const props = withDefaults(defineProps<IProps>(), {
  name: 'Tom',
  age: 18,
  gender: 'male',
})

3. defineEmits 中类型声明

ts
interface IEmit {
  (event: 'customEvent1', payload: string): void
  (event: 'customEvent2'): void
}
const emits = defineEmits<IEmit>()

4. computed 中类型声明

ts
// 和上面的用法相同
const str = computed<string>(() => {
  return 'hello world'
})
const str: ComputedRef<string> = computed(() => {
  return 'hello world'
})