I have 2 classes, one is named "InventoryDTO" and the other is named "Inventory".
The 2 classes store the same properties.. i.e
export class InventoryDto {
id?: number
name: string
active?: boolean
}
The 2 classes are the same, but one of the classes is heavily annotated with decorators (its for the database).
If I return the Inventory to the InventoryDto - I can't get typescript to complain about it because technically its the same properties.
create(dto: CreatInvenoryDto): Promise<InventoryDto> {
// this returns Inventory NOT InventoryDTO - but typescript is fine with it.
return this.dataAccessService.create(dto)
}
I would like it to complain, am I missing something in the tsconfig, I have set strict: true
But still the same, its basically allowing me to return the type even though they are different because they are compatible..
Any way to enforce this?
Thanks
CodePudding user response:
The best you can do is probably to add a "hidden" field:
class Entity {
__type: 'entity' = 'entity';
}
class Dto {
__type: 'dto' = 'dto';
}
class Inventory extends Entity {
id?: number
name: string
active?: boolean
constructor(name: string, id?: number, active?: boolean) {
super();
this.id = id;
this.name = name;
this.active = active;
}
}
class InventoryDto extends Dto {
id?: number
name: string
active?: boolean
constructor(name: string, id?: number, active?: boolean) {
super();
this.id = id;
this.name = name;
this.active = active;
}
}
function save(dto: InventoryDto) {
}
let inv: Inventory;
save(inv);
CodePudding user response:
You could pick the fields you require and return only those. Ignoring TypeScript all together, if you wrote this in plain JS you'd be returning the entire inventory from the create method rather than just those fields which probably isn't what you want.
You could try something like this to retain type safety and only return the required fields:
create(dto: CreatInvenoryDto): Promise<InventoryDto> {
const { id, name, active } = this.dataAccessService.create(dto)
const inventoryDto: InventoryDto = { id, name, active }
return inventoryDto
}
