
기본적인 내용을 잠시 다뤄보려고 한다.
타입스크립트에 대한 정말 기본적인 내용만 앞서 다뤘으므로 전혀 내용을 모른다면 이전 포스팅 을 참고하고 시작하길 바란다.
npx create-react-app [프로젝트 이름] --template typescript
type Imgage , interface ListProps 와 같이
컴포넌트의 props 타입을 명시하여 작성해준다.
만약 property로 유효하지 않은 값이 전달되면 오류를 확인할 수 있다!
import React from "react"
type = Image = {
src: string;
}
interface ListProps {
header: string;
content: string;
image: Image;
}
const List = ({header, content, image}: ListProps) =>{
return(
<div>
{image && <img src={image.src}>}
<header>{header}</header>
<p>{content}</p>
</div>
);
};
초기값을 설정하는 경우라면 자동으로 타입이 지정되므로 명시적으로 타입을 지정할 필요가 없긴하다.
그러나 초기값을 설정할 수 없는 경우 아래와 같이 작성한다.
type ListObj = {
id:string;
header: string;
content: string | null;
image: string | null;
};
const [list, setList] = useState<ListObj | null>(null);
event의 type으로는 React의 이벤트 시스템을 사용하기 때문에 React 버전의 이벤트를 직접 지정해야한다.
외우지 않아도 된다.
태그의 해당 eventHandler 에 마우스를 올려보면 친절히 VS Code에서 알려주긴 한다.
간단하게 3가지 정도만 확인하자.
const handleChange = (e: React.ChangeEvent<HTMLInputElement>)=>{
event.preventDefault();
//로직 작성
}
const handleChange = (e: React.FormEvent<HTMLInputElement>)=>{
event.preventDefault();
//로직 작성
}
const handleChange = (e: React.MouseEvent<HTMLInputElement>)=>{
event.preventDefault();
//로직 작성
}
기본적인 내용만 일단 찍먹 해보았다.
다음 포스팅부터 직접 작업을 해보며 위에 대한 내용을 복습하며 진행해야겟다!