Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
439 views
in Technique[技术] by (71.8m points)

reactjs - React Typescript-类型的参数不能分配给类型的参数(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.

(这是一个使用Typescript和钩子的React应用程序,可将条目捕获为以下简单显示的形式。)

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

(在这里,它在Stackblitz中可以工作,但在本地使用VS代码,但出现setUser(userData);错误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

(我该如何解决此打字稿错误)

  ask by cdmt translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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.

(它会看到您传入了null,因此假定此状态为(并将始终为null)。)

Instead, you need so specify the type, as in:

(相反,您需要这样指定类型,例如:)

interface UserData {
  username: string;
  password: string;
  previousState: null
}

//...
const [user, setUser] = useState<UserData | null>(null);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...