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

246
Views
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 answers
Answer question

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 Report

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 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!