打字稿:如何正确组合不同的类型?

时间:2020-03-28 02:11:05

标签: reactjs typescript

我目前正在使用Typescript构建一个React应用程序。

我有一个组件可以调用以从服务器中获取用户数据(在我的情况下使用firebase), 然后将该数据存储在组件状态中。


// Defining my own custom user type
// I tried to "combine" the two types here
type Partial<T> = {
  [P in keyof T]?: T[P];
};
type MyUserType = Partial<firebase.User> & { myCustomProperty?: string};

// Defining types for component Props and State
type Props = {
  gotUser: boolean;
  userData: firebase.User;
};
type State = {
  currentUser: MyUserType | null;
};

// My component that gets user data and stores it on local state
class App extends React.Component<Props, State> {
  constructor(props: Props) {
    super(props);

    this.state = {
      currentUser: null,
    };
  }

  componentDidMount() {
    getUserData(); // makes server call to fetch user data
  }

  componentDidUpdate() {
    const { gotUser, userData } = this.props;
    if (gotUser) {
      // got user; now save it in component state
      this.setState({
        currentUser: {
          ...userData ,                // spread all of <firebase.User> properties
          myCustomProperty: 'hello',   // ...and also append my own property
        },
      });
    }
  }

  render() {
    return <div>Thank you for any help!</div>
  }
}

我很难为this.state.currentUser定义类型。

我想要做的是拿取从firebase提取的对象(类型为<firebase.User>),然后将其与我定义的任何其他属性组合,最后得到自己的自定义{{1} }类型。

我第一次尝试做

MyUserType

但是在我使用像这样的映射类型之前,编译器给了我一个神秘的错误:

type MyUserType = firebase.User & { myCustomProperty?: string; }

我这样做正确吗?还是有更好的方法来达到相同的结果?

我对Typescript还是很陌生,但是我觉得这个问题(采用现有类型并对其进行自定义)是很常见的问题,而且我以一种怪异的方式解决了它。

1 个答案:

答案 0 :(得分:0)

您可以改为扩展界面

interface MyUserType extends firebase.User {
  myCustomProperty?: string;
}