0

I'm attempting to create a generic table builder class. Within the table builder, I define an anonymous class which stores column definitions. I would like the table builder to store instances of these definitions in an array. Here is the simplified class definition I'm currently working with:

export class TableBuilder<T> {

  Column = class {
    constructor(public data: T) {}
  }

  private columns: Array<TableBuilder['Column']>

  column(data: T) {
    const col = new this.Column(data);
    this.columns.push(col);
  }
}

The line this.columns.push(col) throws a compile-time error: Argument of type '(anonymous class)' is not assignable to parameter of type 'typeof (anonymous class)'

Is there a way to define the columns member as an array of anonymous class instances? I can define it as type any[], but I would prefer a solution that preserves type enforcement of column entries.

1
  • Your code gives different errors in the typescript playground. Can you provide a complete example that shows the errors your getting there? Commented Jun 8, 2020 at 18:39

1 Answer 1

1

You have to define a custom constructor type which produces column objects with a specific interface. Something like that:

interface IColumn<T> {
    //define column interface here
}

interface IColumnConstructor<T> {
    new(data: T): IColumn<T>;
}

class TableBuilder<T> {
    private Column: IColumnConstructor<T> = class<T> {
        constructor(public data: T) { }
    }

    private columns: IColumn<T>[] = [];

    public column(data: T) {
        const instance = new this.Column(data);
        this.columns.push(instance);
    }
}

Your anonymous class<T> class must be compatible with the ColumnInterface<T> interface if this scenario.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.