💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
[TOC] ## 概述 可以对类,属性,方法,参数进行装饰器 ``` declare type ClassDecorator = <TFunction extends Function>(target: TFunction) => TFunction | void; declare type PropertyDecorator = (target: Object, propertyKey: string | symbol) => void; declare type MethodDecorator = <T>(target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<T>) => TypedPropertyDescriptor<T> | void; declare type ParameterDecorator = (target: Object, propertyKey: string | symbol | undefined, parameterIndex: number) => void; ``` ## 示例 ``` function Table(tableName: string){ return (constructor:Function)=> { constructor.prototype.__tableName = tableName; }; } function Column(columnName: string) { return function (target: any, propertyKey: PropertyKey) { if (!target.__columns) { target.__columns = []; } target.__columns.push({ propertyKey, columnName }); }; } @Table('users') class User { @Column('id') id: number; @Column('username') username: string; @Column('age') age: number; constructor(id: number, username: string, age: number) { this.id = id; this.username = username; this.age = age; } save(entity: any) { const tableName = entity.__tableName; const columns = entity.__columns; const columnNames = columns.map((col: any) => col.columnName).join(', '); const values = columns.map((col: any) => `'${entity[col.propertyKey]}'`).join(', '); const query = `INSERT INTO ${tableName} (${columnNames}) VALUES (${values})`; console.log('Generated SQL Query:', query); // 这里可以执行数据库查询操作 } } const user = new User(1, 'JohnDoe', 25); user.save(user); //Generated SQL Query: INSERT INTO users (id, username, age) VALUES ('1', 'JohnDoe', '25') ```