2

The goal is to create a completely type safe generic class such as a Table Class below which would allow to create a Table instance whose field types are given as type parameters (or any other possible means).

let userTable = new Table<number, string, string>(
  columnNames: ["id", "name", "address"],
  fields: [
    [0, "John", "225 Main"],
    [1, "Sam", "330 E Park"]
  ]);
let billsTable = new Table<number, Date, Date>(
  columnNames: ["custId", "invoiceDate", "dueDate", "balance"],
  fields: [ [1, new Date(), new Date()] ]);

The question is, with full type safety in focus, how would you define or implement such a generic type structure which could have unknown number of type parameters?

1

1 Answer 1

2

You can use tuples as your type parameters:

class Table<T extends string, U extends any[]> {
  constructor(columnNames: T[], fields: U[]) {
    /* Do something */
  }
}

If you provide type parameters explicitly, your arguments will be type-checked against them.

new Table<'custId' | 'invoiceDate', [string, number, Date]>(
  ['custId', 'invoiceDate'],
  [
    ['foo', 1, new Date()],
    ['bar', 2, new Date()],
  ]
)

Works with named parameters as well:

class Table<T extends string, U extends any[]> {
  constructor(configuration: { columnNames: T[], fields: U[]}) {
    /* Do something */
  }
}

new Table<'custId' | 'invoiceDate', [string, number, Date]>({
  columnNames: ['custId', 'invoiceDate'],
  fields:[
    ['foo', 1, new Date()],
    ['bar', 2, new Date()],
  ]
})
Sign up to request clarification or add additional context in comments.

2 Comments

This gives compilation errors such as: "An index signature parameter type must be 'string' or 'number' ". Also, try to add other methods or data members to the class and it complains!
That's because I left a broken index signature there. I wanted to see if keys can be established at the call site, but was reminded they cannot — A class can only implement an object type or intersection of object types with statically known members..

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.