-1

I am getting 2 typescript errors for el and modalRoot types. How should I declare el and modalRoot to get rid of typescript errors?

interface IModal {
  closeModal: () => {};
  title: string;
  children: ReactNode
}

const Modal = (props: IModal) => {
const {  closeModal, title, children } = props;
let el = null;
const modalRoot = document.getElementById('modal-root');

useEffect(() => {
  el = React.createElement('div');
  modalRoot.appendChild(el);
  return () => modalRoot.removeChild(el);
}, []);
....
}
Negin Basiri
  • 1,305
  • 2
  • 26
  • 47
  • 1) `modalRoot` could be null if the element doesn't exist 2) `el` is initially null, its type should be explicitly given. – Andrew Li Jun 21 '19 at 05:15
  • My question is what should it be? I am new to typescript – Negin Basiri Jun 21 '19 at 05:25
  • use the [`!` operator](https://stackoverflow.com/questions/42273853/in-typescript-what-is-the-exclamation-mark-bang-operator-when-dereferenci) if you know for a fact the element exists. For the latter, type it. – Andrew Li Jun 21 '19 at 05:30

1 Answers1

0

You can simply add an if statement in your hook:

useEffect(() => {
  el = React.createElement('div');
  if (!!el && !!modalRoot) {
    modalRoot.appendChild(el);
    return () => modalRoot.removeChild(el);
  }
}, []);
zilijonas
  • 3,285
  • 3
  • 26
  • 49