'Cannot find name T
Why I get this error ?
Cannot find name T
Code:
import React from 'react';
function App() {
type person<T> = {
name: T,
age?: T
};
let arr: T[] = [];
const addPerson = (person: T): void => {
arr.push(person);
};
return (
<div className="App">
<button onClick={() => addPerson({name: 'James'})}>Hello World</button>
</div>
);
}
export default App;
Solution 1:[1]
The T is only in scope from where it was defined until the end of that statement. It doesn't have any meaning after that. It also appears you don't know what generics are or how to use them. The person type you have declared takes a generic argument, that argument is a type, and it's declaring that a person has a name and an optional age, which both must be of that type, which clearly doesn't make sense for most types.
Give what you are doing, you don't need the generics at all, you probably just want:
function App() {
type person = {
name: string,
age?: number
};
let arr: person[] = [];
const addPerson = (person: person): void => {
arr.push(person);
};
return (
<div className="App">
<button onClick={() => addPerson({name: 'James'})}>Hello World</button>
</div>
);
}
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 | Jason Kohles |
