一、ref定义类型
const a = ref('') //根据输入参数推导字符串类型 Ref<string>
const b = ref<string[]>([]) //可以通过范型显示约束 Ref<string[]>
const c: Ref<string[]> = ref([]) //声明类型 Ref<string[]>
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<typPeople[]> = 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<string | number>('foo')
foo.value = 123
********* 如果ref类型未知,则建议将 ref 转换为 Ref<T>: *********
function useState<T>(initial: T) {
const state = ref(initial) as Ref<T>
return state
}
const item: typPeople = { name: 'aa', age: 18 }
const x1 = useState(item) // x1 类型为: Ref<typPeople>
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<T>类型,reactive不存在Reactive<T>
//它返回是UnwrapNestedRefs<T>,和传入目标类型一致,所以不存在定义通用reactive类型
function reactiveFun<T extends object>(target: T) {
const state = reactive(target) as UnwrapNestedRefs<T>
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; }
网友评论