TS的类型守卫、类型约束实践
类型守卫
// 基础类型判断
const arr = [30, 50]
console.log(typeof arr) // object
const set = new Set(arr)
console.log(typeof set) // object
const map = new Map()
console.log(typeof map) // objectclass Customer {constructor() {}buy(method:string) {console.log(method) }
}// 获取具体类型方案一 prototype原型 局限性:自定义类无法判断
console.log('arr:', Object.prototype.toString.call(arr)) // [object Array]
console.log('set:', Object.prototype.toString.call(set)) // [object Set]
console.log('map:', (Object.prototype.toString.call(map))) // [object Map]
console.log('CUstomer:', Object.prototype.toString.call(new Customer())) // [object Object]//获取具体类型方案二: 类型守卫-instanceof in 判断指定类型实例
//获取具体类型方案三: 自定义类型守卫
function isCustomer(val:any): val is Customer {return val instanceof Customer
}
console.log('isCustomer', isCustomer(new Customer()))
console.log('isCustomer', isCustomer('aaaa'))
运行结果:

类型约束
class ObjectRefImpl<T extends object, K extends keyof T> {public readonly __v_isRef = trueconstructor(private readonly _obj:T, private readonly _key: K) {}get value() {return this._obj[this._key]}set value(newVal) {this._obj[this._key] = newVal }
}type ObjType = {username: string; age: number}
type KeysType<K> = K extends keyof ObjType ? K : never
type TestKEeysType = KeysType<'username' | 'age'>
const obj = new ObjectRefImpl<ObjType, 'username'>({username: 'curry', age: 23}, 'username');
console.log(obj.value)
运行结果