I'm attempting to create a class hierarchy with a recursive array that references it self, but also correctly assigns type to subclasses.
I think I'm close, but I'm getting an inexplicable TS2351 error
export interface ContentNodeJSON {
id: string
parentId?: string
children: ContentNodeJSON[]
}
export class ContentNode {
id: string
parentId?: string
children: this[]
constructor(model: ContentNodeJSON) {
this.id = model.id;
this.parentId = model.parentId;
this.children = model.children.map(child => new this(child));
}
}
The error is as follows:
This expression is not constructable.
Type 'ContentNode' has no construct signatures. TS2351
20 | this.parentId = model.parentId;
> 21 | this.children = model.children.map(child => new this(child));
| ^
22 | }
Is it just impossible to call a constructor from itself? Is there some other pattern I should be using to accomplish this goal?
Edit:
To clarify what I mean by "correctly assigns type to subclasses", if I define a subclass as:
class Page extends ContentNode {}
Then Page.children needs to be of type Page, not ContentNode.
id: string (children: this[]should bechildren: ContentNode[]