React 限制 Props 和 State 类型

发布时间 2023-03-22 21:10:45作者: Himmelbleu

下面是 Component 的接口,P 代表 Props、S 代表 State。

interface Component<P = {}, S = {}, SS = any> extends ComponentLifecycle<P, S, SS> { }

所以,在 tsx 中写两个类型进行约束就可以了:

import { Component, useState } from "react";

type StateType = {
  date: Date;
};

type PropsType = {
  name?: string;
};

export default class Clock extends Component<PropsType, StateType> {
  constructor(props: PropsType) {
    super(props);
    this.state = {
      date: new Date(),
    };
  }

  render() {
    return (
      <div></div>
    );
  }
}