57 lines
1.3 KiB
TypeScript
57 lines
1.3 KiB
TypeScript
export const exp7 = () => {
|
|
|
|
const userService = new UserService();
|
|
userService.delete(1);
|
|
console.log(userService.getUsers());
|
|
|
|
};
|
|
|
|
type NewType = {
|
|
id: number;
|
|
username: string;
|
|
};
|
|
const parseConf: ((...args: any[]) => any)[] = [];
|
|
|
|
export const parse =
|
|
(parseTo: (...args: any[]) => any) =>
|
|
(target: any, propertyName: string, index: number) => {
|
|
parseConf[index] = parseTo;
|
|
};
|
|
|
|
|
|
class UserService {
|
|
private users: NewType[] = [
|
|
{ id: 1, username: 'admin' },
|
|
{ id: 2, username: 'pincman' },
|
|
];
|
|
|
|
getUsers() {
|
|
return this.users;
|
|
}
|
|
|
|
@parseDecorator
|
|
delete(@parse((arg: any) => Number(arg)) id: number) {
|
|
this.users = this.users.filter((userObj) => userObj.id !== id);
|
|
return this;
|
|
}
|
|
}
|
|
|
|
// 在函数调用前执行格式化操作
|
|
export const parseDecorator = (
|
|
target: any,
|
|
propertyName: string,
|
|
descriptor: PropertyDescriptor,
|
|
): PropertyDescriptor => {
|
|
console.log('开始格式化数据');
|
|
return {
|
|
...descriptor,
|
|
value(...args: any[]) {
|
|
// 获取格式化后的参数列表
|
|
const newArgs = args.map((v, i) =>
|
|
parseConf[i] ? parseConf[i](v) : v,
|
|
);
|
|
console.log('格式化完毕');
|
|
return descriptor.value.apply(this, newArgs);
|
|
},
|
|
};
|
|
}; |