You can use the property decorator to do this:
const DOT_INCLUDES = {}; function DtoInclude(proto, name) { const key = proto.constructor.name; if (DOT_INCLUDES[key]) { DOT_INCLUDES[key].push(name); } else { DOT_INCLUDES[key] = [name]; } } class A { @DtoInclude public x: number; public y: number; @DtoInclude private str: string; constructor(x: number, y: number, str: string) { this.x = x; this.y = y; this.str = str; } toDTO(): any { const includes: string[] = DOT_INCLUDES[(this.constructor as any).name]; const dto = {}; for (let key in this) { if (includes.indexOf(key) >= 0) { dto[key] = this[key]; } } return dto; } } let a = new A(1, 2, "string"); console.log(a.toDTO());
( code on the playground )
You can use the reflection metadata that is used in their examples, if you want, I implemented it with the DOT_INCLUDES registry DOT_INCLUDES that it will work well on the playground, without requiring additional dependencies.
Edit
As @Bergi noted, you can iterate over includes instead of this :
toDTO(): any { const includes: string[] = DOT_INCLUDES[(this.constructor as any).name]; const dto = {}; for (let ket of includes) { dto[key] = this[key]; } return dto; }
Which is really more efficient and makes more sense.
source share