Skip to content

Behavior of subTypes #1370

Open
Open
@kei-hito

Description

@kei-hito

I wourd like to know about the specification of 'subTypes'.
The code below shows the execution of the code described in the README.
I expected the 'album' tyep to be 'UnderWater', but it seems to be 'Album'.
Is there any workaround?

  • source code
export abstract class Photo {
  id!: number;
  filename!: string;
}

export class Landscape extends Photo {
  panorama!: boolean;
}

export class UnderWater extends Photo {
  depth!: number;
}

export class Album {
  id!: number;
  name!: string;

  @Type(() => Photo, {
    discriminator: {
      property: '__type',
      subTypes: [
        { value: Landscape, name: 'landscape' },
        { value: UnderWater, name: 'underwater' },
      ],
    },
  })
  topPhoto!: Landscape | UnderWater;
}

test('test subtype ', () => {
  const albumJson = {
    id: 1,
    name: 'foo',
    topPhoto: {
      id: 9,
      filename: 'cool_wale.jpg',
      depth: 1245,
      __type: 'underwater',
    },
  };
  const album = plainToClass(Album, albumJson);
  console.log('album.topPhoto instanceof Photo: ' + (album.topPhoto instanceof Photo));
  console.log('album.topPhoto instanceof UnderWater: ' + (album.topPhoto instanceof UnderWater));
});
  • console log
      album.topPhoto instanceof Photo: true
      album.topPhoto instanceof UnderWater: false

Metadata

Metadata

Assignees

No one assigned

    Labels

    type: questionQuestions about the usage of the library.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions