在TypeScript中处理可变数量的“类型参数”

问题描述 投票:0回答:1

目标是创建一个完全类型安全的泛型类,例如下面的Table Class,它允许创建一个Table实例,其字段类型作为类型参数(或任何其他可能的方法)给出。

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()] ]);

问题是,如果关注全类型安全性,您将如何定义或实现可能具有未知数量类型参数的通用类型结构?

javascript typescript
1个回答
0
投票

您可以使用元组作为类型参数:

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

如果显式提供类型参数,则会针对它们对您的参数进行类型检查。

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

也适用于命名参数:

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()],
  ]
})
© www.soinside.com 2019 - 2024. All rights reserved.