[英]How do I use “then” with TypeScript?
我正在將 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 函數包裝在上下文中,但實際函數在 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? 有沒有“那么”的東西? 還是有其他方法可以做到這一點?
在 VSCode 中,您可以按 CTRL,將 cursor 移動到updatePassword
上,然后查看函數的定義。 在 function 中使用返回類型而不是void
。
問題是您告訴 TypeScript 關於您的firebase
object 的謊言。
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
class 以獲取有關doPasswordUpdate
的類型信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.