繁体   English   中英

如何在 TypeScript 中使用“then”?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM