Skip to content

Instantly share code, notes, and snippets.

@EpicWink
Created October 11, 2023 06:18
Show Gist options
  • Save EpicWink/6718c422793a7e592f196f23889b788a to your computer and use it in GitHub Desktop.
Save EpicWink/6718c422793a7e592f196f23889b788a to your computer and use it in GitHub Desktop.
Subclass field declaration
import { Expose, Type, plainToClass } from 'class-transformer';
import { Equals, IsString } from 'class-validator';
import 'reflect-metadata';
abstract class FooBar {
@IsString()
@Expose()
type: string;
}
class Foo extends FooBar {
@Equals('foo')
@Expose()
type: 'foo';
}
class Bar extends FooBar {
@Equals('bar')
@Expose()
type: 'bar';
}
class Item {
@Type(() => FooBar, {
discriminator: {
property: 'type',
subTypes: [
{ name: 'foo', value: Foo },
{ name: 'bar', value: Bar },
],
},
keepDiscriminatorProperty: true,
})
@Expose()
fooBar: FooBar;
}
const items: Item[] = [
plainToClass(Item, { fooBar: { type: 'foo' } }),
plainToClass(Item, { fooBar: { type: 'bar' } }),
];
console.log(items);
{
"dependencies": {
"class-transformer": "^0.5.1",
"class-validator": "^0.14.0",
"reflect-metadata": "^0.1.13"
},
"devDependencies": {
"typescript": "^5.2.2"
}
}
{
"compilerOptions": {
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"lib": ["dom", "esnext"],
"module": "commonjs",
"outDir": "dist",
"target": "es2022"
},
"include": ["main.ts"]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment