Cast entity to dto

One possible option is to mark your DTO object with the @Exclude and @Expose decorators and then do a conversion with plainToClass:

@Exclude()
export class PhotoSnippetDto {
   @Expose()
   @IsNumber()
   readonly id: number;

   @Expose()
   @IsString()
   readonly name: string;
}

Assuming you've decorated as above you can then do: const dto = plainToClass(PhotoSnippetDto, photo);

The resulting object is in the form you expect with only id and name showing up on the final object. If you decide later to expose more properties you can simply add them to your DTO and tag them with @Expose.

This approach also allows you to remove the constructor from your DTO that is using Object.assign


So based on Jesse's awesome answer I ended up creating the DTO using @Exclude() and @Expose() to remove all but exposed properties:

import { IsString, IsEmail } from 'class-validator';
import { Exclude, Expose } from 'class-transformer';

@Exclude()
export class PhotoSnippetDto {
   @Expose()
   @IsNumber()
   readonly id: number;

   @Expose()
   @IsString()
   readonly name: string;
}

And then I created a generic transform interceptor that calls plainToclass to convert the object:

import { Injectable, NestInterceptor, ExecutionContext } from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { plainToClass } from 'class-transformer';

interface ClassType<T> {
    new(): T;
}

@Injectable()
export class TransformInterceptor<T> implements NestInterceptor<Partial<T>, T> {

    constructor(private readonly classType: ClassType<T>) {}

    intercept(context: ExecutionContext, call$: Observable<Partial<T>>, ): Observable<T> {
        return call$.pipe(map(data => plainToClass(this.classType, data)));
    }
}

And then use this interceptor to transform the data to any type:

@Get('test')
@UseInterceptors(new TransformInterceptor(PhotoSnippetDto))
test(): PhotoSnippetDto {
  const photo = new Photo({
    id: 1,
    name: 'Photo 1',
    description: 'Photo 1 description',
    filename: 'photo.png',
    views: 10,
    isPublished: true,
    excludedPropery: 'Im excluded'
  });
  return photo;
}

Which gives me what I wanted:

{
  id: 1,
  name: 'Photo 1'
}

Definitely feels more nest-like! I can use the same interceptor where ever I need and to change the response I only ever need to change the DTOs.

Happy days.