Published on

Type error: 'inputFile.current' is possibly 'null'. useRefを使った時のエラーの対象方法

Authors
  • avatar
    Name
    ssu
    Twitter

useRefを使った際に下記のようなtypeエラーが出ました。

Type error: 'inputFile.current' is possibly 'null'.

その時の対象方法を紹介します。例えば、下記のようにuseRefを使ったコードでは、下記のようなbuildエラーが出てしまします。

Failed to compile. ./components/Home.tsx:226:5 Type error: 'inputFile.current' is possibly 'null'.
const Home = () => { const inputFile = useRef(null) const onButtonClick = () => { // `current` points to the mounted file input element inputFile.current.click(); }; return ( <> <input type='file' id='file' ref={inputFile} style={{display: 'none'}}/> <button onClick={onButtonClick}>Open file upload window</button> </> )

そこで、このエラーを解消するため、HTMLElementの型をつけてやり、nullである可能性を考慮したコードにします。

const Home = () => { const inputFile = useRef<HTMLInputElement>(null) // 型を定義する const onButtonClick = () => { // `current` points to the mounted file input element inputFile?.current?.click(); // nullになる可能性を考慮 }; return ( <> <input type='file' id='file' ref={inputFile} style={{display: 'none'}}/> <button onClick={onButtonClick}>Open file upload window</button> </> )

参考: react open file browser on click a div

参考: Typescript, how to pass "Object is possibly null" error?