一愉老、ref定義類型
const a = ref('') //根據(jù)輸入?yún)?shù)推導(dǎo)字符串類型 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) //{} 不是空數(shù)組,而是空對象
list2.value.push({ name: '小張', age: 18 })
console.log('list2-后:', list2.value[0]) //{name: '小張', age: 18}
********* ref 內(nèi)部值指定類型 *********
const foo = ref<string | number>('foo')
foo.value = 123
********* 如果ref類型未知,則建議將 ref 轉(zhuǎn)換為 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{...}
//當(dāng)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參數(shù)只能是對象
const arr = reactive([1, 2]) //數(shù)組,其實結(jié)果還是對象
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>,和傳入目標(biāo)類型一致囱稽,所以不存在定義通用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; }