Grokking TypeScript
Vote

0% completed

​

Typing useState and useEffect

A line as ordinary as useState([]) creates a state that can hold nothing. Try to store a value in it:

import { useState } from "react"; const PostTitles = () => { const [titles, setTitles] = useState([]); return <button onClick={() => setTitles(["Hello"])}>{titles.length}</button>; };
error TS2322: Type 'string' is not assignable to type 'never'.

The compiler infers the type of a state from its initial value. An empty array gives it no information about the items, so the state becomes never[], an array that can contain no items

.....

.....

.....

Like the course? Get enrolled and start learning!

Reading Progress

0%


Vote for new content