Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion src/TransformOperationExecutor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,11 @@ export class TransformOperationExecutor {
return Number(value);
} else if (targetType === Boolean && !isMap) {
if (value === null || value === undefined) return value;
return Boolean(value);
if (this.options.parseBooleanStrings && typeof value === 'string') {
return value.toLowerCase() === 'true' || value === '1';
} else {
return Boolean(value);
}
} else if ((targetType === Date || value instanceof Date) && !isMap) {
if (value instanceof Date) {
return new Date(value.valueOf());
Expand Down
1 change: 1 addition & 0 deletions src/constants/default-options.constant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export const defaultOptions: Partial<ClassTransformOptions> = {
excludePrefixes: undefined,
exposeDefaultValues: false,
exposeUnsetFields: true,
parseBooleanStrings: false,
groups: undefined,
ignoreDecorators: false,
strategy: undefined,
Expand Down
8 changes: 8 additions & 0 deletions src/interfaces/class-transformer-options.interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,4 +76,12 @@ export interface ClassTransformOptions {
* DEFAULT: `true`
*/
exposeUnsetFields?: boolean;

/**
* When set to true, boolean fields with string `true` (case insensitive) or `1` as value will be converted to true, other
* string values will be converted to false.
*
* DEFAULT: `false`
*/
parseBooleanStrings?: boolean;
}
12 changes: 11 additions & 1 deletion test/functional/implicit-type-declarations.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,12 @@ describe('plainToInstance transforms built-in primitive types properly', () => {

@Type()
boolean2: boolean;

@Type()
boolean3: boolean;

@Type()
boolean4: boolean;
}

const result: Example = plainToInstance(
Expand All @@ -114,8 +120,10 @@ describe('plainToInstance transforms built-in primitive types properly', () => {
number2: 100,
boolean: 1,
boolean2: 0,
boolean3: 'true',
boolean4: 'false',
},
{ enableImplicitConversion: true }
{ enableImplicitConversion: true, parseBooleanStrings: true }
);

it('should recognize and convert to Date', () => {
Expand All @@ -140,5 +148,7 @@ describe('plainToInstance transforms built-in primitive types properly', () => {
it('should recognize and convert to boolean', () => {
expect(result.boolean).toBeTruthy();
expect(result.boolean2).toBeFalsy();
expect(result.boolean3).toBeTruthy();
expect(result.boolean4).toBeFalsy();
});
});