1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

React×TypeScriptで、useState<String>('')とするとinputタグのvalueでstateを渡した際にエラーが発生する

Posted at

はじめに

ReactとTypeScriptの初心者が、型で苦戦したのでその内容をメモ。
useStateを用いて、入力フォームのvalueを更新していく処理を記述した際にエラーが発生。

発生したエラーと解決法

修正前のコード

input.tsx
import React, { ChangeEvent, useState, memo } from "react"

const Input = memo(() => {
    const [ contents, setContents ] = useState<String>('')

    const onChangeContents = (e: ChangeEvent<HTMLInputElement>) => {
        setContents(e.target.value)
    }

    return (
        <input type="text" value={contents} onChange={onChangeContents} />
    )
})
export default Input

エラー内容

Type 'String' is not assignable to type 'string | number | readonly string[] | undefined'.
  Type 'String' is missing the following properties from type 'readonly string[]': join, every, some, forEach, and 12 more.

解決方法

エラー文をよく見ると、「String」型は「string」型に割り当てることが出来ないと書いていました。
該当箇所を見てみると、const [ contents, setContents ] = useState<String>('')

「String」型でstateを定義してしまったせいで、inputのvalueに値を入れられなかったのです。
。。。とても初歩的なミスでした(スペルの違いに気付かず、30分も費やしてしまいました。。。)

解決方法としては、該当箇所を以下に変更
const [ contents, setContents ] = useState<string>('')

なんなら、useState('')で空文字を渡している為、型定義をわざわざ行わなくても暗黙的にstring型になるので、
const [ contents, setContents ] = useState('')
こちらでも良いようです。

どちらが良いか分かりませんが、初心者の内は型が明示的に示された方が分かりやすいかなと感じたので、僕の場合は前者で対応しました。

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?