IntrinsicAttributes and IntrinsicClassAttributes

김명성·2022년 3월 25일
0

typescript

목록 보기
2/8

IntrinsicAttributes and IntrinsicClassAttributes

Interfaces는 TypeScript를 사용할 때 구현한다.Interface는 React와 jsx파일, DOM의 상호작용에 영향을 미친다.

기본 원칙

아래의 코드를 본인이 작성했다고 생각해보자.

interface BarProps {
  foo: string;
}

class Bar extends React.Component<BarProps> {
  ...
}

render() {
  return (
    <form>
      <Bar />
    </form>
  );
}

렌더링 할 때 당신은 interface의 typecheck로 인해 Error를 마주할 것이다.
사용하는 컴포넌트는 반드시 interface BarProps의 인자를 가져야하기 때문이다.
즉 컴포넌트는 필수 Props(여기에서는 BarProps)가 있어야 한다.

정상적으로 rendering이 진행되기 위해서는 다음과 같은 작업을 수행해야 한다.

render() {
  return (
    <form>
      <Bar foo="Jack Daniel's"/>
    </form>
  );
}

또는 컴포넌트의 정의 자체를 제거하거나 interface의 foo 프로퍼티를 optional로 만들 수 있다.

class Bar extends React.Component<> {
 ...
}
interface BarProps{
  foo?: string;
}

중요한 점은 일관성을 유지하여 코드를 작성해야 하는 것이다.

IntrinsicAttributes and IntrinsicClassAttributes와 관련된 에러는, 알수 없는 props를 전달하려 하거나 정의 되지 않은 작업을 컴포넌트에 전달하려고 하고 있기 때문이다.

<MyComponent {...props} />의 형태로 props를 전달할 때에는 사용 가능한 모든 props를 가져오는 것을 의미한다.

<MyComponent action={this.state.action} />과 같이 action prop을 명시적으로 호출하면, 오류가 발생한다.

typescript를 사용하며 props를 전달할 때에는, interface 프로퍼티의 타입을 생각하여 전달해야 한다.


https://stackoverflow.com/questions/59969756/not-assignable-to-type-intrinsicattributes-intrinsicclassattributes-react-js

0개의 댓글