Proxy+Reflect+Ts 实现vue3事件侦听器
const fun = <T>(object: Person, key: keyof T): T => {
const proxy = (object: any, key: any) => {
return new Proxy(object, {
get(target, prop, receiver) {
return Reflect.get(target, prop, receiver);
},
set(target, prop, value, receiver) {
return Reflect.set(target, prop, value, receiver);
},
});
};
return proxy(object, key);
};
let a = { name: "haha", age: 20 };
modelFun(a, "name");
a.name = "啦啦";
a.age = 10;
console.log(a); // { name: '啦啦', age: 10 }
Partial(可选类型)
type Person = {
name: string;
age: number;
game: boolean;
};
// 将类型设置为可选类型
type newPerson = Partial<Person>;
// type newPerson = {
// name?: string | undefined;
// age?: number | undefined;
// game?: boolean | undefined;
// };
Pick(筛选类型)
type Person = {
name: string;
age: number;
game: boolean;
};
// 筛选类型为新类型
type pickPerson = Pick<Person, "age" | "name">;
// type pickPerson = {
// name: string;
// age: number;
// };
Readonly(只读类型)
type Person = {
name: string;
age: number;
game: boolean;
};
// 将所有类型变为只读
type readonlyPerson = Readonly<Person>;
// type readonlyPerson = {
// readonly name: string;
// readonly age: number;
// readonly game: boolean;
// };
Record(记录类型)
type Person = {
name: string;
age: number;
game: boolean;
};
// 将旧类型设置成新类型
type children = "A" | "B" | "C";
type recordPerson = Record<children, Person>;
// type recordPerson = {
// A: Person;
// B: Person;
// C: Person;
// };
Infer关键字
// infer关键字 一般和 extends关键字 配合使用
type Type<T> = T extends Array<infer U> ? U : T;
type A = Type<(string | number)[][]>;
let a: A = ["1", 1];
// 可以限制类型
type typeNever<T> = T extends Array<infer U> ? U : never;
type D = typeNever<boolean>; // 不满足条件
// let d: D = true; // 不能将类型“boolean”分配给类型“never”
方法
// 取类型里的某一个类型为新的类型
type Arr = [1, 2, 3];
type First<T extends any[]> = T extends [infer one, infer two, infer three]? one: [];
type c = First<Arr>; // type c = 1;
// 取类型里的最后一个类型为新的类型
type Arr = [1, 2, 3];
type Last<T extends any[]> = T extends [...any, infer Last] ? Last : [];
type a = Last<Arr>; // type a = 3
// 取类型里的第一个类型为新的类型
type Arr = [1, 2, 3];
type First<T extends any[]> = T extends [infer First, ...any[]] ? First : [];
type a = First<Arr>; // type a = 1;
// 删除类型里的第一个类型,其余的组成新类型
type Arr = [1, 2, 3];
type Shift<T extends any[]> = T extends [infer Shift, ...infer newArr] ? newArr : [];
type a = Shift<Arr>; // type a = [2, 3]
// 删除类型里的最后一个类型,其余的组成新类型
type Arr = [1, 2, 3];
type Pop<T extends any[]> = T extends [...infer newArr, infer Pop] ? newArr : [];
type a = Pop<Arr>; // type a = [1, 2]
// 利用递归倒转类型
type Arr = [1, 2, 3];
type Reverse<T extends any[]> = T extends [infer First, ...infer rest]
? [...Reverse<rest>, First]
: T;
type arrReverse = Reverse<Arr>; // type arrReverse = [3, 2, 1]