Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

149
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda