Typescript - 如何创建与接口具有相同属性但具有不同 属性 类型的类型

Typescript - How to create a type with the same properties as an interface, but with different property types

我正在制作查询生成器。我的数据模型如下所示:

export interface SalesOrder {
  id: number
  customerName: string;
  date: Date;
}

在我的查询构建器中,我希望 columns 看起来像这样:

{
  id: 'salesOrder.id',
  customerName: 'customer.name',
  date: 'salesOrder.date',
}

我正在尝试弄清楚如何对 Columns 对象进行通用键入,以便它具有模型中的所有键,但所有类型都是字符串。这样我就可以像 const columns: Columns<SalesOrder> 一样声明它,并且它会理解该对象必须具有与 SalesOrder 模型中相同的所有键,但所有值都是 string

我试过这个:

export interface Columns<T> {
  [alias: keyof T]: string;
}

但它抱怨 keyof T 部分,说“索引签名参数类型必须是 'string' 或 'number'。”

该错误消息的结尾应该是:

Consider using a mapped object type instead.

See the documentation on mapped types.

这是什么意思:

export type Columns<T> = {
  [alias in keyof T]: string;
}

它需要是一个type,因为这实际上是一个映射类型。它遍历 keyof T 的所有可能性并单独评估该联合的每个成员。这在接口中并不真正支持。

[key: MyType]是索引签名。它说对于任何 MyType 都有一个一致类型的值。其中 [key in MyType] 定义映射类型的键。

Playground


或者,您可以尝试 Record 类型。

export type Columns<T> = Record<keyof T, string>

Playground