2021-07-21 수요일
React를 사용할 때 특정 변수가 ReactElement인지 검증할 때 React.isValidElement 함수를 사용한다.
TypeScript에선 Type Guard처럼 쓰면 된다.
node_modules/@types/react/index.d.ts에선 이렇게 타입이 선언되어있고
declare namespace React {
...
function isValidElement<P>(object: {} | null | undefined): object is ReactElement<P>;
...
}node_modules/react/cjs/react.production.min.js를 보면 (minify 되어있음) 소스가 압축된 캔처럼 되어있다.
이 중에 isValidElement를 검색해보면 이런 내용을 볼 수 있다.
exports.isValidElement = L;이제 function L을 찾아보면 이런 내용이고
function L(a) {
return 'object' === typeof a && null !== a && a.$$typeof === n;
}n의 값은 이렇게 되어있다.
n = 60103;사실 github에 올려진 facebook/react 소스를 보면 편하게 볼 수 있다. (링크)
function isValidElement(object) {
{
return (
typeof object === 'object' &&
object !== null &&
object.$$typeof === REACT_ELEMENT_TYPE
);
}
}React.isValidElement 함수는 이런 과정을 수행한다.