I'm new to TS, and I have a question about initializing classes Here example of parsing object
const myObj = {
"square": 100,
"trees": [
{
"height": 100,
"needles": 100500
},
{
"height": 50,
"apples": 20
}
]
};
class Forest {
constructor(
public square: number,
public trees: (Pine | AppleTree)[]
) {}
}
class Tree {
constructor(
public height: number,
) {}
}
class Pine extends Tree {
constructor(
public height: number,
public needles: number,
) {
super(height);
}
}
class AppleTree extends Tree {
constructor(
public height: number,
public apples: number,
) {
super(height);
}
public getApples() {
console.log(this.apples);
}
}
export function initMyClass() {
const forest: Forest = myObj;
}
But here is a compilation error - myObject Type is not assignable to type 'Forest'. How can I parse object to that class?
And how to determine what subclass of Tree
should be used to parse particular object in array
I tried interfaces, but, maybe not in a right way