Imagine you have a class defined as follows:
Class Flower {
public readonly color: string;
public readonly type: string;
constructor(color: string, type: string) {
this.color = color;
this.type = type;
}
Now, let's introduce another class called FlowerDto, which mirrors the Flower class in structure but is intended to represent a Data Transfer Object (Dto). The field names of FlowerDto are subject to change based on external factors, but for now they align with those of Flower.
Class FlowerDto {
public readonly color: string;
public readonly type: string;
constructor(color: string, type: string) {
this.color = color;
this.type = type;
}
In Typescript, it is possible to define a function like this:
function getFlower(): Flower {
return new FlowerDto("red", "rose");
}
Is there a way to prevent Typescript from allowing this behavior? Such inconsistencies can be detected at compile time and may lead to confusion and costly errors if not addressed promptly.
I have considered the possibility of a compiler option in tsconfig that disables implicit casting (casting without specifying the "any" keyword), but my search has been futile so far. Any assistance on this matter would be greatly appreciated.