Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to pass a string as a generic in TypeScript

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’."

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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'>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading