Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

142
Views
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'."

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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'>
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!