반응형
TypeScript를 사용할 땐 props의 타입은 서로 동일해야만 오류가 발생하지 않습니다! 이때 타입을 정의하는 방법에 대해 포스팅하겠습니다~
📌 예시 코드
// 부모 코드
function App() {
const [datas, setDatas] = useState<apiType[]>([]);
const [listLength, setListLength] = useState<number>(0);
return (
<section className="main-container">
<h1 className="aria-hidden">Seoul Restaurant Website</h1>
// props 전달
<ShowList list={datas} listLength={listLength} />
</section>
);
}
// 자식 코드
// props 타입 정의하기
type ShowListProps = {
list: apiType[];
listLength: number;
};
// 타입 적정하기(: 사용)
function ShowList({ list, listLength }: ShowListProps) {
return (
<div className="store-list-container">
<StoreTable list={list} />
</div>
);
}
// 컴포넌트 타입 정의하기
type storeTableProps = {
list: apiType[];
endPage: number;
startPage: number;
};
// 타입 적용하기
function StoreTable({ list, startPage, endPage }: storeTableProps) {
return (
<table>
<thead className="store-table-header">
<tr>
<th className="store-name-title">가게명 / 업태명</th>
<th className="store-vegetable-title">채식 가능</th>
</tr>
</thead>
<tbody className="store-table-data">
{storeList.map((store) => {
return (
<tr key={store.CRTFC_UPSO_MGT_SNO}>
<td className="store-name-data">
<button type="button" className="link">
{store.UPSO_NM.length > 12
? store.UPSO_NM.slice(0, 13).concat("...")
: store.UPSO_NM}
<span className="store-kind">
{store.BIZCND_CODE_NM}
<span className="mobile-state-show">
{store.CGG_CODE_NM}
</span>
</span>
</button>
</td>
<td className="store-vegetable-data">
<span></span>
</td>
</tr>
);
})}
</tbody>
</table>
);
}
함수가 아닌 컴포넌트에서 매개변수수의 타입은 부모 코드와 동일한 Type으로 정의해줘야 합니다.
1. type 키워드로 타입 집합을 정의합니다.
2. : TYPE를 사용해서 알맞은 컴포넌트에 적용합니다.
함수에서는 매개변수에 직접 : TYPE을 적용해주면 됩니다. 자세한 내용은 TypeScript 3일 차(함수 형성하기)를 참고해주시면 될 것 같습니다.
728x90
'TypeScript' 카테고리의 다른 글
React에 TypeScript 적용하기 (0) | 2023.08.30 |
---|---|
서울 음식점 API의 Type 정의하기 (0) | 2023.08.29 |
TypeScript 3일차 (함수 형성하기) (0) | 2023.08.29 |
TypeScript 2일차 (변수 생성 방법) (0) | 2023.08.21 |
TypeScript 1일차 (사용하는 이유와 장점) (0) | 2023.08.19 |