如何解决打字稿不断向我抱怨的 属性 声明错误?

How do I solve this property declaration error that typescript keeps complaining to me?

我的 componentDidMount 生命周期函数中有一段代码执行以下操作

this.unsubscriber = auth().onAuthStateChanged((user: RNFirebase.User) => {
   this.setState({ user });
});

onAuthStateChanged returns 一个取消订阅函数,需要在组件卸载时调用。问题是,如果我像这样声明取消订阅者变量

constructor(props: {}) {
    super(props);
    this.unsubscriber: Function = null
}

typescript 抱怨说 属性 "unsubscriber" 不存在(而且我无法分配给函数,因为它是常量或只读 属性)。我尝试做其他事情,比如将它作为状态传递。

type AppState = {
  user: RNFirebase.User | null;
  unsubscriber: Function | null;
}

class App extends Component<{}, AppState> {
   ....
}

但这对我没有任何好处;当我尝试从 onAuthStateChanged 分配 return 值时出现相同的错误。 this.unsubscriber = null 如果我只是在没有打字稿的情况下做出反应,那会很好用,但我正在尝试同时使用两者。

我得到的最接近的是这个

type AppState = {
  user: RNFirebase.User | null;
};

class App extends Component<{}, AppState> {
  private unsubscriber: Function;
  ....
}

但是我得到的这个错误是它没有在那里或在构造函数中初始化,我不能为它分配 null。那我该怎么办?

这是我正在使用的完整代码。

import React, { Component } from 'react';
import { Text, View } from 'react-native';
import { auth, RNFirebase } from 'react-native-firebase';
import { Login } from './screens';

type AppState = {
  user: RNFirebase.User | null;
};

class App extends Component<{}, AppState> {
  private unsubscriber: Function; // This has to be initialized.

  constructor(props: {}) {
    super(props);
    this.state = { user: null };
  }

  componentDidMount() {
    this.unsubscriber = auth().onAuthStateChanged((user: RNFirebase.User) => {
      this.setState({ user });
    });
  }

  componentWillUnmount() {
    if (this.unsubscriber) {
      this.unsubscriber();
    }
  }

  render() {
    const { user } = this.state;

    if (!user) {
      return <Login />;
    }

    return (
      <View>
        <Text>Welcome to my awesome app {user.email}!</Text>
      </View>
    );
  }
}

export default App;

我建议您将 unsubscriber 声明保留为 class 成员,但将其设为可选 (optional class properties). Also, Function type is generally not useful at all (just take a look at what is the interface that it defines) and you're better off defining its type as () => void if its return value is going to be ignored (see callback types)。所以,尝试这样的事情:

private unsubscriber?: () => void;

你只需要初始化unsubscriber 属性:

private unsubscriber: (() => void) | null = null;