Home:ALL Converter>Typescript errors when using React hooks

Typescript errors when using React hooks

Ask Time:2021-01-18T18:33:25         Author:georg199041

Json Formatter

I'm trying to use react useState, useRef hooks with the typescript in Ionic app, and constantly having silly typescript errors when trying to access object properties.

const [ matrix, updateMatrix ] = useState([]);
updateMatrix([['cell1', 'cell2', 'cell3'], ['cell4', 'cell5', 'cell6']])

In the code above I'm getting

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

const basketEl = useRef(null);
if (basketEl.current) { 
  console.log(basketEl.current.getBoundingClientRect())
}

In the above code I'm getting "Object is possibly 'null'" for basketEl.current. Even if I put

if (basketEl.current !== null) {

the error still present. The interesting thing is that if I do not use hooks and use react classes, typescript errors go away. It takes a lot of time to fix ts errors, and I gave up and started to use classes. Maybe I'm using hooks wrong? Do someone have the same problems using hooks and typescript together?

Author:georg199041,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/65772816/typescript-errors-when-using-react-hooks
thSoft :

You have to specify the exact types of the states because they are ambiguous based on the default values.\nCorrect code:\nconst [ matrix, updateMatrix ] = useState<string[]>([]);\n\nconst basketEl = useRef<Element>(null);\n",
2021-01-18T10:44:16
user14698598 :

const [ matrix, updateMatrix] = useState<any>([])\nHave you tried this",
2021-01-20T03:55:20
yy