如何在打字稿声明中指定类型参数?

时间:2019-10-22 11:42:44

标签: reactjs typescript

我创建了一个React组件,该组件接受其子组件的类。该组件负责为用户提供通过OIDC协议登录的功能,如果用户已登录,则将子对象传递给用户对象作为道具(子对象将在API调用中使用它)。

这是声明我的组件的方式:

type AuthProps = {
  childClass: typeof React.Component;
}

type AuthState = {
  user: Maybe<User>
}

class Auth extends React.Component<AuthProps, AuthState> {
}

然后我将子元素渲染为:

<this.props.childClass user={this.state.user} />

此配置工作正常。但是,如果我想要更多类型的安全性怎么办?也就是说,是否要确保childClass支持user道具?我试图像这样输入:

  childClass: typeof ReactComponent<{user: Maybe<User>}>,

但是,这甚至不是正确的语法。可以以某种方式缩小childClass的类型吗?

1 个答案:

答案 0 :(得分:1)

替代1: React.ComponentType

type AuthProps = {
  childClass: React.ComponentType<{ user: Maybe<User> }>;
};

class Auth extends React.Component<AuthProps, AuthState> {
  render() {
    return <this.props.childClass user={this.state.user} />;
  }
}

React.ComponentType是一种内置类型(代替了typeof React.Component),并允许同时使用类或函数组件。

替代项2: Render Props

type AuthProps2 = {
  childClass: (user: Maybe<User>) => JSX.Element;
};

class Auth2 extends React.Component<AuthProps2, AuthState> {
  render() {
    return this.props.childClass(this.state.user);
  }
}

这是首选且更安全的选择。假设客户通过了

之类的内联组件
const App = () => <Auth childClass={props => <div>{props.user}</div>} />;

,它可以防止第一个解决方案的性能下降。替代方法1会在每个渲染周期中重新安装组件,因为组件实例每次都会更改(有关文章请参见here)。