Skip to content

fix: Boolean Type Transformation goes wrong #711

Closed
@somehowchris

Description

@somehowchris

Description

Using @Type(() => Boolean does not work as advertised here.

Minimal code-snippet showcasing the problem
I have a minimal app to show the whole scenario https://github.com/somehowchris/nestjs-query-validation-failing

Doing:

curl --location --request POST 'http://localhost:3001/?name=Chris&external=false&age=12' \
--header 'Content-Type: application/json' \
--data-raw '{
    "name":"Chris",
    "external": "false",
    "age": "12"
}'

Should transform "false" to the type Boolean with false

import { Type } from 'class-transformer';
import { IsBoolean, IsInt, IsPositive, IsString } from 'class-validator';

export class AppSearchQuery {
  @IsString()
  public name: string;
  @IsBoolean()
  @Type(() => Boolean)
  public external: boolean;
  @IsInt()
  @IsPositive()
  @Type(() => Number)
  public age: number;
}

Which again should result in the return body

{
    "name": "Chris",
    "external": false,
    "age": 12
}

but results in this

{
    "name": "Chris",
    "external": true,
    "age": 12
}

Expected behavior

The boolean should be transformed with its actual value.

Actual behavior

As shown the boolean value is true which should be false.

Activity

added
status: needs triageIssues which needs to be reproduced to be verified report.
type: fixIssues describing a broken feature.
on May 2, 2021
diffy0712

diffy0712 commented on May 14, 2024

@diffy0712

Hello @somehowchris,

This works as expected. Any non-empty string value is transformed to boolean true by Javascript.
You can force the 'correct' behavior, that you expect with a custom transformer.
Example:

@Transform(({ value }) => {
  if (value === 'true') return true;
  if (value === 'false') return false;
  return value;
})

There is a feature issue on allow casting of primitive values during transformation #550.

github-actions

github-actions commented on Jun 14, 2024

@github-actions

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

locked as resolved and limited conversation to collaborators on Jun 14, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    status: needs triageIssues which needs to be reproduced to be verified report.type: fixIssues describing a broken feature.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @somehowchris@diffy0712

        Issue actions

          fix: Boolean Type Transformation goes wrong · Issue #711 · typestack/class-transformer