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

251
Vistas
Generic Type in an array throws "Cannot find name 'T' "

I have this code:

interface Process<T> {
  first: () => T[];
  second: (d: T) => void;

}

const PROCESSES: Process<T>[] = [
  {
    first: () => [{car: "car1"}],
    second: (car: {car: string}) => {},

  },
  {
    first: () => [{person: "person1"}],
    second: (person: {car: string}) => {}, // => How to make TS mark this as an error because is not a persona type?
  },
];

TS Playground

The problem is that TypeScript throws this error: Cannot find name 'T'.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You use the generic name T when you define the interface or type. You cannot use it to declare types of variables. You need to create a type/interface for Car and Person and use them in the declaration of PROCESSES instead of T.

interface Process<T> {
  first: () => T[];
  second: (d: T) => void;
}

type Car = { car: string };
type Person = { person: string };

const PROCESSES: (Process<Car> | Process<Person>)[] = [
  {
    first: () => [{ car: 'car1' }],
    second: (car: Car) => {}, // => works
  },
  {
    first: () => [{ person: 'person1' }],
    second: (person: Person) => {}, // => works
  },
  {
    first: () => [{ person: 'person1' }],
    second: (person: Car) => {}, // => Error!
];

about 4 years ago · Juan Pablo Isaza Denunciar

0

If you don't want to manually specify all the types of the elements in the processes array, you can use a factory function like this:

function createProcesses<
  T extends any[]
  >(process: [...{ [I in keyof T]: { first: () => T[I][], second: (d: T[I]) => void } } ]){
  return process
}

Playground

const processes = createProcesses([
  {
    first: () => [{ car: 'car1' }],
    second: (car: Car) => {}, // => works
  },
  {
    first: () => [{ person: 'person1' }],
    second: (person: Person) => {}, // => works
  },
  {
    first: () => [{ person: 'person1' }],
    second: (person: Car) => {}, // => Error!
  }
])
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