user3330840
user3330840

Reputation: 7369

Handling variable number of "type parameters" in TypeScript

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?

Upvotes: 2

Views: 1427

Answers (1)

Karol Majewski
Karol Majewski

Reputation: 25780

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()],
  ]
})

Upvotes: 2

Related Questions