안녕하세요
TypeScript 사용 예시: useState, JSDoc, Type in Type 본문
useState에 적용
type PostsObject = {
id: number;
name: string;
hobbyList: any[]
};
const [posts, setPosts] = useState<PostsObject[]>([]);
=> posts state 배열에 들어갈 object의 proeprty type 을 지정
=> null, any보다는 명확한 타입 기재
JSDoc에서 매개변수와 return 값 적용
/**
* 함수 설명
* @param {PostsObject[]} posts
* @return {number}
*/
const getLowestPrice = (posts: PostsObject[]): number => {
console.log(posts)
};
=> @param {타입} 매개변수이름
=> @return {타입}
(posts: PostsObject[]) => posts는 배열이고, 배열의 각 요소는 PostsObject[]의 type을 따라야 한다.
: number => return 값의 type은 number여야 한다.
Type 내에서 또다른 Type 적용
type PostsObject = {
id: number;
list: ListObject[];
};
type ListObject = {
id: number;
subject: string;
};
=> PostsObject 객체의 프로퍼티 중 list 에는 배열의 요소로 ListObject Type 객체를 포함해야한다.
props에 적용
const Supplies = ({numberArray}: {numberArray: number[]}) => {
=> number를 요소로 가지는 배열 props를 비구조화 할당하여 type을 지정