Home > Software engineering >  Typescript --- Type 'string' is not assignable to type 'never'
Typescript --- Type 'string' is not assignable to type 'never'

Time:03-21

I got this error while using typescript.

Type 'string' is not assignable to type 'never'.

It works fine on javascript.

const [gifList, setGifList] = useState([])

const sendGif = async () => {
    if (inputValue.length > 0) {
        console.log('Gif link:', inputValue)
        setGifList([...gifList, inputValue])
        setInputValue('')
    } else {
        console.log('Empty input. Try again')
    }
}

Could you please tell me how to properly declare a type in Typescript.

CodePudding user response:

const [gifList, setGifList] = useState([])

Since you havn't defined the type here, typescript makes its best guess. It sees that you set the state to an array, but it doesn't know what's supposed to be inside that array, so the best it can do is to treat the state as never[].

useState is a generic, so you can use that to specify the type of state:

const [gifList, setGifList] = useState<string[]>([])
  • Related