Skip to content

fix: exposeDefaultValues does not work #1609

Open
@js-d-coder

Description

@js-d-coder

Description

Please consider this code:

import "reflect-metadata";
import { Expose, plainToInstance } from "class-transformer";
import { IsNumber } from "class-validator";

class IMDB {
    @IsNumber()
    @Expose()
    rating: number = 0;

    @IsNumber()
    @Expose()
    votes: number;

    @IsNumber()
    @Expose()
    id: number;
}

const plainObj = {
    votes: 1000,
    id: 1
};

const movie1 = plainToInstance(IMDB, plainObj, {
    excludeExtraneousValues: true,
    enableImplicitConversion: true,
    exposeUnsetFields: false,
    exposeDefaultValues: false,
});

console.log(movie1); // IMDB { rating: 0, votes: 1000, id: 1 }

As you can notice IMDB class has a property rating with default value. Sometimes I want the instance object to not have default value if the property is missing and sometimes I do.
To achieve this using exposeDefaultValues: false option if I don't want default value for the missing property.
exposeDefaultValues: false seems to not be working in above code snippet.

Expected behavior

Default value should not be set to rating property i.e. rating property should not have value of 0 and should not be present in movie1 object.

Actual behavior

'ratingproperty has default value set inmovie1` object.

Metadata

Metadata

Assignees

No one assigned

    Labels

    type: fixIssues describing a broken feature.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions