添加 @types/react@types/react-dom 即可获得完整的 React Web 支持

组件 props

通过 interface 定义组件的参数类型:

interface MyButtonProps {
  title: string;
  disabled: boolean;
}
 
function MyButton({ title, disabled }: MyButtonProps) {
  return (
    <button disabled={disabled}>{title}</button>
  );
}

State

1.默认根据传入的初始值推断类型:

// 推断类型为 "boolean"
const [enabled, setEnabled] = useState(false);

2.也可手动指定 state 的类型:

type Status = "idle" | "loading" | "success" | "error";
 
const [status, setStatus] = useState<Status>("idle");

子元素

给 children 添加类型:

// 宽泛类型
interface ModalRendererProps {
  children: React.ReactNode;
}
 
// 只包括 JSX 元素,而不包括 JavaScript 原始类型,如 string 或 number
interface ModalRendererProps {
  title: string;
  children: React.ReactElement;
}

DOM 事件

给事件添加不同的类型 React.xxxEvent<触发的元素类型>,如:

function handleChange(event: React.ChangeEvent<HTMLInputElement>) {
  setValue(event.currentTarget.value);
}