Created
October 11, 2023 06:18
-
-
Save EpicWink/6718c422793a7e592f196f23889b788a to your computer and use it in GitHub Desktop.
Subclass field declaration
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"dependencies": { | |
"class-transformer": "^0.5.1", | |
"class-validator": "^0.14.0", | |
"reflect-metadata": "^0.1.13" | |
}, | |
"devDependencies": { | |
"typescript": "^5.2.2" | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Show hidden characters
{ | |
"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