PropTypes
PropTypes run-time에 오류를 잡아내준다.
production에서는 오류를 표시하지 않는다.
TypeScript
TypeScript는 컴파일 시간에 props의 type을 검사한다.
그리고 잘못된 type에 대해 IDE에서 즉각적으로 경고를 볼 수 있는데
당연히 npm run build를 하면 실패한다.
차이점
TypeScript는 API요청의 결과를 알 수 없다.
이는 런타임에 실행되는 코드이며 TypeScript는 이미 해당 시점에 JS코드로 변환되어 있다.
Propstype은 런타임에 체크할 수 있다.
모두 적용하는 방법 1
import React from "react";
import PropTypes, { InferProps } from "prop-types";
const BlogCardPropTypes = {
title: PropTypes.string.isRequired,
createdAt: PropTypes.instanceOf(Date),
authorName: PropTypes.string.isRequired,
};
type BlogCardTypes = InferProps<typeof BlogCardPropTypes>;
const BlogCard = ({ authorName, createdAt, title }: BlogCardTypes) => {
return <span>Blog Card</span>;
};
BlogCard.propTypes = BlogCardPropTypes;
export default BlogCard;
모두 적용하는 방법 2
(babel-plugin-typescript-to-proptypes)
import React from "react";
type Props = {
title: string;
createdAt: Date;
authorName: string;
};
const BlogCard = ({ title, createdAt, authorName }: Props) => {
return <span>Blog card</span>;
};
export default BlogCard;
----> 변환 ---->
import React from 'react'
import PropTypes from 'prop-types'
const BlogCard = ({ title, createdAt, authorName }) => {
return <span>Blog card</span>;
};
BlogCard.propTypes = {
title: PropTypes.string.isRequired,
createdAt: PropTypes.instanceOf(Date),
authorName: PropTypes.string.isRequired,
}
export default BlogCard