Custom array function doesn't work
Description
similar to #216, when I am trying run the example code (example3) below, it's complaining photo.albums.findByName is not a function
import 'es6-shim';
import 'reflect-metadata';
import { Type, Transform, Expose } from 'class-transformer';
import { plainToInstance, plainToClass } from 'class-transformer';
class Album {
id: string;
name: string;
}
class AlbumArray extends Array<Album> {
findByName(name: string) {
return this.find(album => album.name === name);
}
}
class Photo {
id: string;
filename: string;
description: string;
tags: string[];
@Type(() => Album)
albums: AlbumArray;
}
let photoJson = {
id: '1',
filename: 'myphoto.jpg',
description: 'about my photo',
tags: ['me', 'iam'],
albums: [
{
id: '1',
name: 'My life',
},
{
id: '2',
name: 'My young years',
},
],
};
let photo = plainToClass(Photo, photoJson);
console.log('deserialized object: ', photo);
console.log('-----------------------------');
console.log('Trying to find album: ', photo.albums.findByName('My life'));
console.log('-----------------------------');
Expected behavior
print out the return of the findByName
Actual behavior
photo.albums.findByName is not a function
Firstly, you are not transforming the value of albums to AlbumArray it will remain Album[]:
@Transform(({ value }) => new AlbumArray(...value))
Secondly, something is wrong with this inheritance in TypeScript. This works fine in the browser, not in TypeScript:
class PowerArray extends Array {
isEmpty() {
return this.length === 0;
}
}
const arr = new PowerArray(1, 2, 5, 10, 50);
console.log(arr.isEmpty());
EDIT:
Works fine on TS Playground but not on CodeSandbox.
looks like it's not aligned with the documentation: https://github.com/typestack/class-transformer#working-with-arrays
and official example: https://github.com/typestack/class-transformer/blob/develop/sample/sample3-custom-arrays/Photo.ts#L15
It seems like @Type() is applying the intended "child type" to the parent object?
I'm working with Maps, and I've resorted to just using @ValidateNested() and manually re-assigning my maps as proper Map<K,V>()s.