Among the various cake classes, I have a function that returns an instance of one of them. My goal is to somehow change the variable to match the actual type of the returned value.
// Classes
class Cake{
myName: string;
base: string = "vanilla"
frosting: string = "empty"
constructor(myName: string) {
this.myName = myName
}
}
class Chocolate extends Cake{
frosting: string = "chocolate"
cut() {
console.log("cut to 8 pieces!")
}
}
class Strawberry extends Cake {
frosting:string="strawberry"
topping:string="coconut"
}
// Functions
function getCake(frosting:string, myName:string):Chocolate|Strawberry {
const chocolateClass = new Chocolate(myName)
const strawberryClass = new Strawberry(myName)
const classes:any = { chocolateClass, strawberryClass }
let returnedObj: Chocolate|Strawberry;
Object.keys(classes).forEach((key) => {
if (classes[key].frosting == frosting) {
returnedObj = classes[key]
}
})
return returnedObj
}
// Logic
const myCake: Strawberry | Chocolate = getCake("chocolate", "John")
console.log(myCake.frosting) // able to access
console.log(myCake.myName) // able to access
myCake.cut() // able to access, but with linting error and intellisense issue
I can access specific properties from the strawberry
class,
However, the problem arises with linting and intellisense not recognizing the existing properties and methods. This led me to consider recasting the myCake
variable based on the return type of the getCake()
function. How can I achieve this?
I want to avoid creating separate functions for each cake type (getStrawberryCake()
), especially when dealing with multiple cake classes.