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: discriminate based on which properties, rather than the value of one? #1520

Open
bdarcus opened this issue Apr 30, 2023 · 1 comment
Labels
type: question Questions about the usage of the library.

Comments

@bdarcus
Copy link

bdarcus commented Apr 30, 2023

I have an array of contributors on an author, and other similar, properties.

I would like to be able to discriminate between Organization and Person Contributors, without having to adding a common property to the JSON.

Here's the code:

export abstract class Contributor {
	name: string;
    
    constructor(name: string) {
        this.name = name;
    }
}

export class Organization extends Contributor {
	name: string;
	location?: string;

	constructor(name: string, location?: string) {
		super(name);
		this.location = location;
	}

	sortName(): string {
		return this.name;
	}
}

export class Person extends Contributor {
	name: string;
	familyName: string;
	givenName: string;

	constructor(name: string, givenName: string, familyName: string) {
		super(name);
		this.givenName = givenName;
		this.familyName = familyName;
	}

	displayName(initialize: boolean): string {
		return `${this.givenName} ${this.familyName}`;
	}

	sortName(): string {
		return `${this.familyName}, ${this.givenName}`;
	}
}

... and then, on a Reference class:

	@Type(() => Contributor, {
    discriminator: {
      property: 'type',
      subTypes: [
        { value: Person, name: 'person' },
        { value: Organization, name: 'organization' },
    ],
    },
  })
	author?: (Person | Organization)[];

And it all works, except I'd rather not add the "type" property, since I already know how to distinguish them based on their properties.

This particular model is likely to be edited by humans, so I want to keep the JSON schema I export from it as clean as possible.

So is there a way to have my cake and eat it too?

Or alternately, have a default mapping, if the type property isn't there?

@bdarcus bdarcus added the type: question Questions about the usage of the library. label Apr 30, 2023
@diffy0712
Copy link

hello @bdarcus,

currently I am not aware of such feature. You should always provide the discriminator field. You could write a getter on your plain object, which would return the type based on your logic.

But I think it is always cleaner to be explicit and give it a type if it means a different thing, but that is a personal preference.

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

2 participants