LoginSignup
3
2

More than 3 years have passed since last update.

null の可能性がないことを TypeScript コンパイラに伝える方法

Posted at

次の TypeScript コードはコンパイルエラーが発生します。

import { useEffect, useRef } from 'react';

const MyComponent = () => {
  const ref = useRef<HTMLDivElement>(null);
  useEffect(() => {
    const div = ref.current;
    console.log(div.style.display);
  });
  return <div ref={ref}></div>;
};

export default MyComponent;

コンパイルエラーは次のような内容です。

TypeScript error in /Users/.../MyComponent.tsx(7,17):
Object is possibly 'null'.  TS2531

     5 |   useEffect(() => {
     6 |     const div = ref.current;
  >  7 |     console.log(div.style.display);
       |                 ^
     8 |   });
     9 |   return <div ref={ref}></div>;
    10 | };

ref.currentの型がHTMLDivElement | nullであり、nullの可能性があるため発生したエラーだとわかります。

しかし、上記コードではref.currentnullになることはありません。理由は、レンダリング時にref.currentに値が代入され、ref.currentの参照場所であるuseEffect(() => { /* ここ */ })は必ずレンダリング後に実行されるからです。

nullnull!に変更することでコンパイラエラーを抑制できます。

import { useEffect, useRef } from 'react';

const MyComponent = () => {
  const ref = useRef<HTMLDivElement>(null!);
  useEffect(() => {
    const div = ref.current;
    console.log(div.style.display);
  });
  return <div ref={ref}></div>;
};

export default MyComponent;

このようにnull!と書くことで、TypeScript コンパイラに「この変数には一時的に null を入れているだけであって、参照時に null になることはない」と伝えることができます。

次のページを参考にしました。

React+TypeScript Cheatsheets

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2