I am getting a TypeScript 2417 error on the Table class implementing the following code:
export abstract class BaseTable {
protected constructor() {}
static Builder = class<T extends BaseTable> {
protected constructor() {}
build(): T {
return this.buildTable();
}
protected buildTable(): T {
throw new Error("Must be implemented in subclasses");
}
};
}
export class Table extends BaseTable {
private constructor() {
super();
}
static Builder = class extends BaseTable.Builder<Table> {
protected constructor() {
super();
}
static create() {
return new Table.Builder();
}
protected buildTable(): Table {
return new Table();
}
};
}
This produces the error
Class static side 'typeof Table' incorrectly extends base class static side 'typeof BaseTable'.
The types returned by '(new Builder()).build()' are incompatible between these types.
Type 'Table' is not assignable to type 'T'.
'Table' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'BaseTable'.(2417)
My goal is to have private or protected constructors and to be able to call the code in 2 steps
const builder = Table.Builder.create();
const table = builder.build();
I thought this might be caused by the Builder
class being static so I have tried this:
export abstract class BaseTable {
constructor() {}
}
export namespace BaseTable {
export abstract class Builder<T extends BaseTable> {
protected constructor() {}
build(): T {
return this.buildTable();
}
protected abstract buildTable(): T;
}
}
export class Table extends BaseTable {
constructor() {
super();
}
}
export namespace Table {
export class Builder extends BaseTable.Builder<Table> {
protected constructor() {
super();
}
static create() {
return new Table.Builder();
}
protected buildTable(): Table {
return new Table();
}
}
}
This code produces the same error and defeats the purpose of having private constructors.
Can someone explain this error to me and how to implement this code.