[Typescript] Type and Interface for performance

发布时间 2023-10-10 15:05:35作者: Zhentiw

Let's say you're creating a component that has all the props of input but needs to add a label prop. You'll need to extend from the ComponentProps type helper

import { ComponentProps } from "react";
 
export type InputProps =
  ComponentProps<"input"> & {
    label: string;
  };
 
export function Input({
  label,
  ...props
}: InputProps) {
  return (
    <label>
      {label}
      <input {...props} />
    </label>
  );
}

But unfortunately, intersections used this way will, on the scale of a large codebase, slow TypeScript down.

Instead, you should use an interface, using interface extends:

import { ComponentProps } from "react";
 
export interface InputProps
  extends ComponentProps<"input"> {
  label: string;
}

 

See article for more details