question: skipping "optional and undefined" attributes

Author: VincentCoucharriereCreated Aug 18, 2025Updated Jan 25, 2026
Labelstype: question

Hi, I was trying to convert a plain js object to a class instance, using plainToInstance method and I wanted to configure this class-transformer function in order to NOT include in the result instance class any optional attribute that was not set or was set to undefined int the provided plain object. I am trying this thanks to the "exposeUnsetFields=fales" ClassTransformOptions option.

However, it does not work : the generated class instance includes the attributes set to undefined. I was expecting to NOT set at all that attribute.

Could you please clarify whether it is possible ? And if so, how ? Thanks in advance for your help, Regards

See demo:

import 'reflect-metadata';
import { plainToInstance } from 'class-transformer';
import { IsOptional, validate, ValidationError } from 'class-validator';

class TestClass {
  @IsOptional()
  name?: string;
}

function handleErr(errors: ValidationError[]): void {
  if (errors && errors.length > 0) {
    throw new Error('class validation failed');
  }
}

const a = plainToInstance(TestClass, {});
const b = plainToInstance(TestClass, { name: undefined });

async function runTest() {
  await validate(a).then(handleErr);
  console.log(a);
// TestClass { name: undefined }
  await validate(b).then(handleErr);
  console.log(b);
// TestClass { name: undefined }
}

runTest().catch(console.error);

Source: typestack/class-transformer