如何在 TypeScript 中将字符串作为泛型传递

How to pass a string as a generic in TypeScript

我想创建一个通用类型,我可以使用它来将普通类型转换为符合我的 API 响应结构的类型。所以问题是我有一堆类型,我想从它们中推断出另一堆看起来像这样的类型:

// this is a type that i have
interface IModel {
  key1: string
  key2: string
}

//this is a type I want to infer
interface IModelResponse {
  model: {
    key1: string
    key2: string
  }
}

// the way i want to do this is through generics in TypeScript
// so let's say something like this:
type IModelResponse = IBaseResponse<IModel, 'model'>

我试过这样的事情:

export interface IBaseResponse<T, modelName extends string> {
  [key: modelName]: T
}

但它给我一个错误“索引签名参数类型必须是 'string' 或 'number'”。

有没有什么我不明白的,或者这不可能按照我想要的方式实施?非常感谢您的帮助!

可以使用in关键字实现

interface IModel {
  key1: string
  key2: string
}

type BaseResponse<T, ModelName extends string> = {
  [key in ModelName]: T
}

type IModelResponse = BaseResponse<IModel, 'model'>