Home > Software engineering >  Generic Type in an array throws "Cannot find name 'T' "
Generic Type in an array throws "Cannot find name 'T' "

Time:05-18

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'.

CodePudding user response:

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

CodePudding user response:

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!
  }
])
  • Related