LoginSignup
33
21

More than 3 years have passed since last update.

useRefをTypeScriptで使うと Object is possibly 'null'. と怒られる件の対策

Posted at

TypeScript で useRef を使おうとすると初期値に null を渡していることもあり useEffect の中で Object is possibly 'null'. 怒られてしまう

個人的なケースとして、 hogehoge.current.scrollTo(0, 0) を要素に適用したかったのだがタイトルの通りとなった

Object is possibly 'null'.
  1. useRefにDOMの型をつける
  2. nullの場合の処理をいれる

上記ですぐに解決できた。

今回のサンプル

scrollTo()を使うサンプルです。

sample.tsx
import React, { FC, useRef } from "react";
import "./styles.css";

const App: FC = () => {
  const refSample = useRef(null);
  const resetScroll = () => refSample.current.scrollTo(0, 0);

  return (
    <div ref={refSample} className="scroll">
      <div className="scroll__box">スクロールできます</div>
      <button onClick={resetScroll}>スクロールトップ</button>
    </div>
  );
};

export default App;

style.css
.scroll {
  width: 300px;
  height: 100px;
  background-color: #e0e0e0;
  overflow-x: scroll;
}

.scroll__box {
  width: 300px;
  height: 500px;
  color: #fff;
  background-color: blue;
}

この状態ではタイトルのエラーが生じます。

1. useRefを使うタイミングで型をつける

sample.tsx
  const refSample = useRef(null); //からの
  const refSample = useRef<HTMLDivElement>(null);

useRef を初期化するには null が一般的で、 null に対して HTMLDivElement の型付けを行う。
初期化された後にDOMの中で ref={sampleRef} として HTMLDivElement が sampleRef.current の中に格納されることとなる。
.current は useRef のデフォルトで決まっているプロパティのキーのこと。

しかしこれだけではまだエラーは消えない。

2. nullの場合の処理をいれる

TypeScriptの型推論として HTMLDivElement or null の可能性があるため、まだ怒られてしまう。

sample.tsx
  const resetScroll = (): void => refSample.current.scrollTo(0, 0); //からの
  const resetScroll = (): void => refSample.current?.scrollTo(0, 0); 

そのため refSample.current?.hogehoge と ? を追加することで短いコードで null の可能性を表すことで怒られなくなる。

codesandbox: https://codesandbox.io/s/vigorous-bas-e3f5l?fontsize=14&hidenavigation=1&theme=dark

33
21
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
33
21