August 24, 2021
TypeScript에 대해 알아보자!
TypeScript는 공식 페이지에서 javascript의 superset이라고 소개한다. 공식문서에 따르면 TypeScript 2.1 부터 —target ESNext를 지원하니, 웬만한 js 문법은 전부 사용할 수 있고 컴파일을 통해 타입체크도 할 수 있으니 superset이라고 부를 수 있겠다.
컴포넌트의 prop 타입을 지정하는 방법은 크게 2가지가 있다.
import React from 'react';
interface GreetingProps {
name: string;
mark: string;
}
const Greeting: React.FC<GreetingProps> = ({ name, mark, optional }) => {
return (
<div>
Hello {name} {mark}
</div>
);
};
Greeting.defaultProps = {
mark: '!',
};
const App = () => {
return (
<Greeting name="YeongJong" /> // Property 'mark' is missing in type
);
};const로 선언한 함수에서 React.FC<GreetingProps> 와 같이 제네릭 방식으로 타입을 설정할 수 있다.
2번 참고자료: https://github.com/typescript-cheatsheets/react/issues/87
import React from 'react';
interface GreetingProps {
name: string;
mark: string;
}
function Greeting({ name, mark, optional }:GreetingProps) => {
return (
<div>
Hello {name} {mark}
</div>
);
};
Greeting.defaultProps = {
mark: '!',
};React.FC는 defaultProps가 적용되지 않는 문제점 그리고, children이 기본 적용되어 있기 때문에 children이 삽입되지 않는 경우에 문제가 발생할 수 있다. 따라서 function 키워드를 통한 type 설정을 권장한다.