Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Typescript - Argument of type is not assignable to parameter of type

I have a demo here

It's a React app using Typescript and hooks to capture entries into form that are simple displayed below.

Here in Stackblitz it works but locally I am using VS code and I get an error for setUser(userData); the error is

const userData: {     username: string;     password: string;     prevState: null; } Argument of type '{ username: string; password: string; prevState: null; }' is not assignable to parameter of type '(prevState: null) => null'.   Type '{ username: string; password: string; prevState: null; }' provides no match for the signature '(prevState: null): null'.ts(2345) 

How can I fox this typescript error

like image 440
cdmt Avatar asked Dec 01 '19 13:12

cdmt


People also ask

Is not assignable to parameter of type TS?

The error "Argument of type string | undefined is not assignable to parameter of type string" occurs when a possibly undefined value is passed to a function that expects a string . To solve the error, use a type guard to verify the value is a string before passing it to the function.

Is not assignable to parameter of type String TypeScript?

The "Type 'string' is not assignable to type" TypeScript error occurs when we try to assign a value of type string to something that expects a different type, e.g. a more specific string literal type or an enum. To solve the error use a const or a type assertion.


2 Answers

const [user, setUser] = useState(null); 

Since you havn't given this a type, typescript has to try to infer it. It sees you passed in a null, so it assumes this state is (and always will be) null. Instead, you need to specify the type, as in:

interface UserData {   username: string;   password: string;   prevState: null }  //... const [user, setUser] = useState<UserData | null>(null); 
like image 132
Nicholas Tower Avatar answered Sep 20 '22 02:09

Nicholas Tower


If you fetching data from API you need this:

import React, { useState, useEffect } from 'react' import axios from 'axios';  const MyComponent = () => { const [data, setData] = useState<any | null>(null); const fetchData = () => { (...) //Axios.get() or async if u await data. setData(fetchData) } } useEffect(() =>{     fetchData() }, []) 
like image 30
Oscar Corona Avatar answered Sep 24 '22 02:09

Oscar Corona