'Typescript --- Type 'string' is not assignable to type 'never'

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 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nicholas Tower