Home > Software engineering >  How to pass a string as a generic in TypeScript
How to pass a string as a generic in TypeScript

Time:05-24

I want to create a generic type that I can use to transform normal type into a type that complies with my API response structure. So the issue is that I have bunch of types and I want to infer off of them another bunch of types that will be look something like this:

// 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'>

I tried something like this:

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

but it gives me an error "An index signature parameter type must be either 'string' or 'number'."

is there something i don't get, or is this impossible to implement in the way that I intend? Would appreciate some help!

CodePudding user response:

It can be implemented using the in keyword

interface IModel {
  key1: string
  key2: string
}

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

type IModelResponse = BaseResponse<IModel, 'model'>
  • Related