Skip to content

Commit

Permalink
feat: add type arguments in transform decorator
Browse files Browse the repository at this point in the history
  • Loading branch information
kitimark committed Jan 11, 2025
1 parent a073b5e commit 3ecf59f
Show file tree
Hide file tree
Showing 4 changed files with 44 additions and 5 deletions.
17 changes: 17 additions & 0 deletions sample/sample6-type-arguments/app.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { plainToInstance, Transform } from '../../src';

interface CSVInvoiceRecord {
net: string;
}

class Invoice {
@Transform<CSVInvoiceRecord, 'net', number>(({ value }) => Number(value.replace(',', '')))
net: number;
}

const rawInvoice: CSVInvoiceRecord = {
net: '2,000',
};

const invoice = plainToInstance(Invoice, rawInvoice);
console.log(invoice);
4 changes: 2 additions & 2 deletions src/decorators/transform.decorator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ import { TransformFnParams, TransformOptions } from '../interfaces';
*
* Can be applied to properties only.
*/
export function Transform(
transformFn: (params: TransformFnParams) => any,
export function Transform<T extends Record<string, any> = any, K extends keyof T = any, R = any>(
transformFn: (params: TransformFnParams<T, K>) => R,
options: TransformOptions = {}
): PropertyDecorator {
return function (target: any, propertyName: string | Symbol): void {
Expand Down
6 changes: 3 additions & 3 deletions src/interfaces/metadata/transform-fn-params.interface.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { TransformationType } from '../../enums';
import { ClassTransformOptions } from '../class-transformer-options.interface';

export interface TransformFnParams {
value: any;
export interface TransformFnParams<T extends Record<string, any> = any, K extends keyof T = any> {
value: T[K];
key: string;
obj: any;
obj: T;
type: TransformationType;
options: ClassTransformOptions;
}
22 changes: 22 additions & 0 deletions test/functional/custom-transform.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -783,6 +783,28 @@ describe('custom transformation decorator', () => {
}).not.toThrow();
});

it('should serialize json to invoice instance of class Invoice with type arguments', () => {
defaultMetadataStorage.clear();
expect(() => {
interface CSVInvoiceRecord {
net: string;
}

class Invoice {
@Transform<CSVInvoiceRecord, 'net', number>(({ value }) => Number(value.replace(',', '')))
net: number;
}

const rawInvoice: CSVInvoiceRecord = {
net: '2,000',
};

const invoice = plainToInstance(Invoice, rawInvoice);
expect(invoice).toBeInstanceOf(Invoice);
expect(invoice.net).toEqual(2000);
}).not.toThrow();
});

it('should serialize a model into json', () => {
expect(() => {
instanceToPlain(model);
Expand Down

0 comments on commit 3ecf59f

Please sign in to comment.