class-transformer icon indicating copy to clipboard operation
class-transformer copied to clipboard

question: How is excludeExtraneousValues different than the excludeAll strategy?

Open mwanago opened this issue 3 years ago • 4 comments

I was trying to make sure that the plainToClass function removes all of the properties that are not specified in the class. It looks like we can do it in two ways.

  1. Use the excludeAll strategy:
import { Expose, plainToInstance } from 'class-transformer';

class UserModel {
  @Expose()
  id: number;
  @Expose()
  name: number;
  @Expose()
  email: string;
}

const instance = plainToInstance(
  UserModel,
  {
    id: 1,
    name: 'John',
    email: '[email protected]',
    unknownProperty: 'unknown',
  },
  {
    strategy: 'excludeAll',
  }
);
  1. Use the excludeExtraneousValues option:
import { Exclude, Expose, plainToInstance } from 'class-transformer';

class UserModel {
  @Expose()
  id: number;
  @Expose()
  name: number;
  @Expose()
  email: string;
}

const instance = plainToInstance(
  UserModel,
  {
    id: 1,
    name: 'John',
    email: '[email protected]',
    unknownProperty: 'unknown',
  },
  {
    excludeExtraneousValues: true,
  }
);

Ideally, I would like a solution where we don't have to use the @Expose() decorator on every property we want to expose if we use -excludeExtraneousValues, but that does not seem to be the case.

It looks like there is no difference between using excludeExtraneousValues and excludeAll. Am I missing something?

mwanago avatar Sep 01 '22 02:09 mwanago

Tagging @nimaen :pray:

mwanago avatar Sep 01 '22 02:09 mwanago

Hello,

I've the exact same question. I also tried to set @Expose() at class level, but withtout success.

Korhm avatar Nov 24 '22 14:11 Korhm

I encountered the same problem, It would be nice to be able to use @Expose() at the class level, instead of having to decorate each property.

eldoccc avatar Feb 08 '24 10:02 eldoccc

Cross linking another issue discussing largely the same thing:

  • #740

Edit: I found the whitelist option on class-validator package does what we want, here.

karlkeefer avatar Jun 24 '24 19:06 karlkeefer