'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?
},
];
The problem is that TypeScript throws this error: Cannot find name 'T'.
Solution 1:[1]
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!
];
Solution 2:[2]
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
}
const processes = createProcesses([
{
first: () => [{ car: 'car1' }],
second: (car: Car) => {}, // => works
},
{
first: () => [{ person: 'person1' }],
second: (person: Person) => {}, // => works
},
{
first: () => [{ person: 'person1' }],
second: (person: Car) => {}, // => Error!
}
])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | cSharp |
| Solution 2 |
