我正在将React应用程序从纯JS转换为TypeScript。它连接到firebase;firebase函数位于一个单独的文件中。我目前正在研究的是允许用户更改他们的密码。我有一个接受新密码并保存它的表单(也有一些验证,但我省略了它)。在纯js中,这一切都很好,但当我转换到TypeScript时,我陷入了如何处理"then"部分。
到目前为止,我的js文件如下:
PasswordForm.js(所以这本来是一个js文件,我把它改成了tsx;我已经添加了几个接口并使用了它们,但我只改变了这些):
import React, {useState} from 'react';
import { withFirebase } from '../Firebase';
interface FormProps {
firebase: {
doPasswordUpdate: (string) => void // Not sure about this line
}
}
interface FormState {
password: string
}
const INITIAL_STATE: FormState = {
password: ""
};
const ChangePasswordForm = ({ firebase }: FormProps) => {
const [formValues, setFormValues] = useState(INITIAL_STATE);
const handleSubmit = event => {
firebase
.doPasswordUpdate(formValues.password)
.then(() => { // THIS IS WHERE THE PROBLEM HAPPENS
... do other things ...
})
.catch(error => {...});
};
return (
<form
onSubmit={handleSubmit}>
<input
name="password"
value={formValues.password}
/>
<button type="submit">Submit</button>
</form>
);
export default withFirebase(ChangePasswordForm);
我的firebase函数被包装在Context中,但实际的函数是在firebase.js中(我没有做任何事情将其转换为TypeScript):
import app from 'firebase/app';
import 'firebase/auth';
import 'firebase/database';
const config = {...}; // Firebase keys etc
class Firebase {
constructor() {
app.initializeApp(config);
this.auth = app.auth();
this.db = app.database();
}
doPasswordUpdate = password =>
this.auth.currentUser.updatePassword(password);
}
export default Firebase;
我得到的错误(在VSCode中)是:
Property 'then' does not exist on type 'void'.
大概是因为我说过doPasswordUpdate应该返回void,它显然没有"then"财产。但是我应该用什么来代替void呢?有没有什么东西是有"然后"的?还是有别的办法?
问题是你在告诉TypeScript关于firebase
对象的谎言。
interface FormProps {
firebase: {
doPasswordUpdate: (string) => void // Not sure about this line
}
}
显式地告诉代码doPasswordUpdate
没有返回值。
相反,你应该通过导入类的声明,然后使用它。
// import the class declaration
import Firebase, { withFirebase } from '../Firebase';
interface FormProps {
// tell the compiler that your firebase is a Firebase
firebase: Firebase
}
这样,编译器就知道要查看Firebase
类以获取有关doPasswordUpdate
的类型信息。
在VSCode中,您可以按CTRL,将光标移动到updatePassword
上并查看函数的定义。在函数中使用返回类型而不是void
。