[React Typescript] Ensure correct inference for prop types with satisfies & ComponentProps

import { ComponentProps } from "react";
import { Equal, Expect } from "../helpers/type-utils";

const buttonProps = {
  type: "button",
  // @ts-expect-error
  illegalProperty: "I AM ILLEGAL",
} as const satisfies ComponentProps<'button'>;

<>
  <button {...buttonProps}>Click Me!</button>
</>;

const buttonPropType = buttonProps.type;

type test = Expect<Equal<typeof buttonPropType, "button">>;

In this example, you can omit as const, it still works

 

-- 

 

Another example

import { ComponentProps } from "react";

const buttonPropsMap = {
  reset: {
    className: "bg-blue-500 text-white",
    type: "reset",
    // @ts-expect-error
    illegalProperty: "whatever",
  },
  submit: {
    className: "bg-gray-200 text-black",
    type: "submit",
    // @ts-expect-error
    illegalProperty: "whatever",
  },
  next: {
    className: "bg-green-500 text-white",
    type: "button",
    // @ts-expect-error
    illegalProperty: "whatever",
  },
} satisfies Record<string, ComponentPros<"button">>;

type ButtonProps = {
  variant: keyof typeof buttonPropsMap;
};

export const Button = (props: ButtonProps) => {
  return <button {...buttonPropsMap[props.variant]}>Click me</button>;
};

const Parent = () => {
  return (
    <>
      <Button variant="next"></Button>
      <Button variant="reset"></Button>
      <Button variant="submit"></Button>

      {/* @ts-expect-error */}
      <Button variant="something"></Button>
      {/* @ts-expect-error */}
      <Button></Button>
    </>
  );
};

 

posted @ 2023-08-07 15:02  Zhentiw  阅读(9)  评论(0编辑  收藏  举报