Experimenting with routing-controllers
and its built-in class-transformer feature, I tried creating an interface for executing a search query based on either a location id
or location coordinate
. My aim was to utilize a discriminated union as a body parameter, but encountered issues where it did not function as expected. (Refer to the latest console output to understand what I mean by 'not working')
For instance:
interface LocationCoordinates {
type: 'coordinate'
longitude: number
latitude: number
}
interface LocationId {
type: 'id'
id: number
}
class LocationRadius {
data: LocationCoordinates | LocationId
searchRadiusInKm: number
}
// raw input for LocationCoordinates
const rawLocationCoordinates = {
data: {
longitude: 22,
latitude: 33
},
searchRadiusInKm: 30
}
// raw input for LocationId
const rawLocationId = {
data: {
id: 1
},
searchRadiusInKm: 30
}
// transform both raw inputs
const realLocationCoordinates = plainToClass(LocationRadius, rawLocationCoordinates);
const realLocationId = plainToClass(LocationRadius, rawLocationId);
console.log({
coordinateType: realLocationCoordinates.data.type, // expects 'coordinate' but receives 'undefined'
idType: realLocationId.data.type // expects 'id' but receives 'undefined'
});
Is there a way to make this work?