【问题标题】:How do I use "then" with TypeScript?如何在 TypeScript 中使用“then”?
【发布时间】:2021-05-13 09:02:23
【问题描述】:

我正在将 React 应用程序从纯 JS 转换为 TypeScript。它与火力基地相关联; 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?有没有“那么”的东西?还是有其他方法可以做到这一点?

【问题讨论】:

标签: javascript reactjs typescript firebase


【解决方案1】:

问题是你在告诉 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 的类型信息。

【讨论】:

    【解决方案2】:

    在 VSCode 中,您可以按 CTRL,将光标移到 updatePassword 上并查看函数的定义。在你的函数中使用返回类型而不是void

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-02
      • 2021-05-12
      • 1970-01-01
      • 1970-01-01
      • 2019-06-27
      • 2015-03-25
      • 2020-10-28
      • 2014-08-04
      相关资源
      最近更新 更多