vue3+ts 中 ref与reactive 指定类型

一、ref定义类型

const a = ref('') //根据输入参数推导字符串类型 Ref
const b = ref([]) //可以通过范型显示约束 Ref
const c: Ref = ref([]) //声明类型 Ref 


const list = ref([1, 3, 5])
console.log('list前:', list.value)
list.value[1] = 7
console.log('list后:', list.value)

type typPeople = {
  name: string
  age: number
}
const list2: Ref = ref([])
console.log('list2-前:', list2.value) //{} 不是空数组,而是空对象
list2.value.push({ name: '小张', age: 18 })
console.log('list2-后:', list2.value[0]) //{name: '小张', age: 18}

********* ref 内部值指定类型 *********
const foo = ref('foo')
foo.value = 123

********* 如果ref类型未知,则建议将 ref 转换为 Ref: *********

function useState(initial: T) {
  const state = ref(initial) as Ref
  return state
}
const item: typPeople = { name: 'aa', age: 18 }
const x1 = useState(item) // x1 类型为: Ref
const x2 = ref(item) //x2 类型为: Ref<{ name:string; age: number;}>
console.log('ref.value:', x1.value, x1.value.name) 
//Proxy{name: 'aa', age: 18}  aa

二、reactive定义类型

const count = ref(1)
console.log('ref:', count) //RefImpl{...}

//当ref分配给reactive时,ref将自动解包
const obj = reactive({ a: count }) //不需要count.value
console.log(obj.a) // 1
console.log(obj.a === count.value) // true
//obj.b=7 //添加属性会报错 // { a: number; }上不存在属性b

//const str=reactive("aaa")   //这是报错的,reactive参数只能是对象
const arr = reactive([1, 2]) //数组,其实结果还是对象
const obj = reactive({ 0: 1, 1: 2 })
console.log('arr', arr) //Proxy {0: 1, 1: 2}
console.log('obj', obj) //Proxy {0: 1, 1: 2}

//reactive定义和ref不同,ref返回的是Ref类型,reactive不存在Reactive
//它返回是UnwrapNestedRefs,和传入目标类型一致,所以不存在定义通用reactive类型
function reactiveFun(target: T) {
  const state = reactive(target) as UnwrapNestedRefs
  return state
}
type typPeople = {
  name: string
  age: number
}
const item: typPeople = { name: 'aa', age: 18 }
const obj1 = reactive(item) //obj1 类型为: { name: string; age: number; }
const obj2 = reactiveFun(item) //obj2 类型为: { name: string; age: number; }

你可能感兴趣的:(vue3+ts 中 ref与reactive 指定类型)