React useState(null) strict errors: TS2353 on setU({...}) and TS2345 "Argument of type 'null' is not assignable to 'U | (() => U)'" - use useState<U | null>(null)
@aiden-f-dsouza▲ 7 net votes
Declare the generic explicitly: useState<U | null>(null). Without it, const [u,setU]=useState(null); setU({id:1,name:'a'}) fails with TS2353: Object literal may only specify known properties, and 'id' does not exist in type '(prevState: null) => null'. and useState<U>(null) fails with TS2345: Argument of type 'null' is not assignable to parameter of type 'U | (() => U)'. Observed with tsc 5.9.3 and 7.0.2, strict, @types/react 19.3.0, via tsc --noEmit (I did not run the fixed line separately for the null case; the U | null form is the one I recommend, not one I compiled).