[TS] Destructing

(a:number)({a} : {a:number})의 차이

리액트와 타입스크립트를 이용해 투두 리스트를 만드는 중에 궁금한 것이 생겼다.

1
2
3
4
5
6
7
8
9
10
11
12
13
// 1
const TodoList = (list: Array<Todo>) => {
return (
...
);
};

//2
const TodoList = ({list} : { list: Array<Todo> }) => {
return (
...
);
};
1
2
3
4
5
6
7
8
9
10
const TodoPage = () => {
...
return(
<Main>
<h2>할일 목록</h2>
...
<TodoList list={todos} />
</Main>
);
}

위와 같이 TodoList를 작성하고 TodoPage에서 list를 넘겨주려고 했을 때, 1번처럼 작성하면 다음과 같은 에러가 발생한다.

“Type { list: Todo[]; } is not assignable to type ‘IntrinsicAttributes & Todo[]’.\n Property ‘list’ does not exist on type ‘IntrinsicAttributes & Todo[]’.”

그러나 2번처럼 작성하면 에러가 발생하지 않는다.
무슨 차이지? IntrinsicAttributes라는 키워드로 타입스크립트 공식 문서도 찾아봤지만 내가 원하는 답은 없었다.
그러다가 머릿속을 스친 문장 하나가 있었다.

타입스크립트에서 구조분해할당은 어떻게 하지?

생각해보니 함수의 인자 부분을 ({ list }) 로 받는 건 일반 js에서는 구조분해할당을 할 때 사용하는 문법이었다.
그래서 destructing으로 다시 검색했다.

Destructuring also works in function declarations. For simple cases this is straightforward:

1
2
3
4
type C = { a: string; b?: number };
function f({ a, b }: C): void {
// ...
}

타입스크립트라고 너무 어렵게 생각한 게 문제였다.

Author

Kahee

Posted on

2022-11-18

Updated on

2022-11-22

Licensed under

Comments