npx create-react-app 프로젝트명 --template typescript
import { useState } from "react";
function App() {
const [name, setName] = useState("");
const [guests, setGuests] = useState([]);
const changeNameHandler = (e) => {
setName(e.target.value);
};
const submitHandler = (e) => {
e.preventDefault();
if (name === "") {
return;
}
setGuests([...guests, name]);
};
return (
<>
<h1>Guest Lists</h1>
<form onSubmit={submitHandler}>
<input type={"text"} value={name} onChange={changeNameHandler}></input>
<button> Add Guest</button>
</form>
<ul>
{guests.map((guest) => {
return <li>{guest}</li>;
})}
</ul>
</>
);
}
export default App;
이러한 에러들이 나타난다.
import { useState } from "react";
function App() {
const [name, setName] = useState<string>("");
const [guests, setGuests] = useState<string[]>([]);
const changeNameHandler = (e: React.ChangeEvent<HTMLInputElement>) => {
setName(e.target.value);
};
const submitHandler = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
if (name === "") {
return;
}
setGuests([...guests, name]);
};
return (
<>
<h1>Guest Lists</h1>
<form onSubmit={submitHandler}>
<input type={"text"} value={name} onChange={changeNameHandler}></input>
<button> Add Guest</button>
</form>
<ul>
{guests.map((guest) => {
return <li>{guest}</li>;
})}
</ul>
</>
);
}
export default App;
이런식으로 useState와 파라미터에도 타입을 지정해주어야한다.