Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

question: how to provide a type for each array element individually #1749

Open
egarkavy opened this issue Aug 29, 2024 · 0 comments
Open

question: how to provide a type for each array element individually #1749

egarkavy opened this issue Aug 29, 2024 · 0 comments
Labels
type: question Questions about the usage of the library.

Comments

@egarkavy
Copy link

egarkavy commented Aug 29, 2024

I was trying to make a class that holds an array of base classes which may be of different inherited types.
I tried to use @type decorator and assumed there is a way to get an internal 'current' element of the array to be parsed but instead (and it's logical) I get a parent object where property which I put @type decorator is defined
Please check a code snipped below: aggregate object which stores an array of actions to do and these actions may be of 2 types


export enum Action {
    Add = 'ADD',
    Delete = 'DELETE'
}

export class ManageChildEntitiesDto {
    @IsString()
    public parentEntityId: string;

    @IsArray()
    @ValidateNested()
    @Type((tho) => {
        if (!tho) {
            return ChildActionDto;
        }

        switch ((tho.object as ChildActionDto).action) { //This type cast is not correct due to tho.object is acually of ManageChildEntitiesDto  type. So the following code will not fall into any of case blocks
            case Action.Add:
                return AddActionDto;
            case Action.Delete:
                return DeleteActionDto;
        }
    })
    actions: (AddActionDto | DeleteActionDto)[];
}

export class ChildActionDto {
    @IsEnum(Action)
    action: Action;
}

export class AddActionDto extends ChildActionDto {
    override action: Action.Add;

    newEntity: UpsertFeatureVariantDto;
}

export class DeleteActionDto extends ChildActionDto {
    override action: Action.Delete;

    id: string;
}

So during debugging it's clearly seen that the tho.object is a parent object rather than a particular array item
image

Please, help me to figure out how to use this @type decorator so that I can tell class transformer what nested type to use for each array item.

@egarkavy egarkavy added the type: question Questions about the usage of the library. label Aug 29, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
type: question Questions about the usage of the library.
Development

No branches or pull requests

1 participant