[SOLVED] Typescript — Type 'string' is not assignable to type 'never'

Issue

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.

Solution

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[]>([])

Answered By – Nicholas Tower

Answer Checked By – Cary Denson (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *