TEL - 10 : Type 'null' is not assignable to type 'Element | DocumentFragment'

TEL - 10 : Type 'null' is not assignable to type 'Element | DocumentFragment'

TypeScript


  • SITUATION :

    • React18 을 기반으로 한 타입스크립트 적용시 index.tsx에서 계속 다음과 같은 오류가 떴다.

    • null 값은 할당할 수 없다는 오류이다.
  • REASON :

    • 실제로 값이 있다는 것은 알고 있지만 TypeScript의 타입 추론 결과에서는 null 값과 같은 알 수 없는 타입에 대한 정보라서 그렇다.
  • SOLUTION :

    • 이렇게 element 부분을 따로 정의해 Type assertion을 추가해주면 된다.
    import ReactDOM from 'react-dom/client'
    import GlobalStyles from '@/styles/GlobalStyles'
    import Router from '@/Router'
    
    const element = document.getElementById('root') as HTMLElement
    const root = ReactDOM.createRoot(element)
    root.render(
      <>
        <GlobalStyles />
        <Router />
      </>,
    )
    
    • const root = ReactDOM.createRoot(document.getElementById('root')!) 이런식으로
      느낌표로(Non-null 단언 연산자) 해줄수도 있지만, eslint에서는 사용을 허용하지 않는다.

© 2022.02 by sunnyfterrain