如何声明 Polymorphic Component 支持 as 属性并推断正确 Props

解读

国内一线/二线前端面试中,「多态组件」是高频深挖点。
面试官真正想确认三件事:

  1. 你是否理解「as」只是运行时决定渲染元素/组件,而 TypeScript 要在编译期把「新元素」的 Props 与「自身额外 Props」做合并。
  2. 你是否能写出既安全又可复用的类型,而不是 any 一把梭。
  3. 你是否知道把 ref 转发、默认元素、样式类名、事件处理等边界情况都考虑进去。
    现场通常会让你「手写一个 Button,支持 as='a'、as='div'、as={RouterLink},同时能自动提示 href、target 或 to 等属性」。答不上来会直接被判定为「TS 能力弱」。

知识点

  1. 泛型约束:keyof JSX.IntrinsicElements | ComponentType。
  2. 条件类型与映射类型:提取「as 元素」对应的 Props。
  3. 交叉类型:把「自身 Props」与「元素 Props」合并,并剔除冲突 key(如 as 组件本身也带 variant?需要 Omit)。
  4. 默认泛型参数:让不传 as 时自动推断为默认元素(如 button)。
  5. PolymorphicRef 工具类型:把 Ref 类型也按 as 元素做映射,保证 forwardRef 不丢失类型。
  6. 实战注意:事件类型兼容性(button vs a vs div 的 onClick 签名差异)、静态属性继承(displayName/defaultProps)、服务端渲染安全(as 为自定义组件时避免未序列化 props)。

答案

import React, { ElementType, ComponentPropsWithRef, forwardRef } from 'react';

type AsProp<C extends ElementType> = {
  as?: C;
};

type PropsToOmit<C extends ElementType, P> = keyof (AsProp<C> & P);

export type PolymorphicComponentProps<
  C extends ElementType,
  Props = {}
> = AsProp<C> &
  Omit<ComponentPropsWithRef<C>, PropsToOmit<C, Props>> &
  Props & {
    ref?: ComponentPropsWithRef<C>['ref'];
  };

// 以 Button 为例
type ButtonProps<C extends ElementType> = PolymorphicComponentProps<
  C,
  { variant?: 'primary' | 'secondary'; size?: 'sm' | 'md' | 'lg' }
>;

type ButtonComponent = <C extends ElementType = 'button'>(
  props: ButtonProps<C>
) => React.ReactElement | null;

export const Button: ButtonComponent = forwardRef(
  <C extends ElementType = 'button'>(
    { as, variant = 'primary', size = 'md', ...rest }: ButtonProps<C>,
    ref?: ComponentPropsWithRef<C>['ref']
  ) => {
    const Component = as || 'button';
    return <Component ref={ref} data-variant={variant} data-size={size} {...rest} />;
  }
) as ButtonComponent;

// 使用
<Button>原生按钮</Button>
<Button as="a" href="/home" target="_blank">链接按钮</Button>
<Button as={RouterLink} to="/profile" variant="secondary">路由按钮</Button>

以上代码在 VSCode 中可自动补全 href、target、to 等属性,ref 也能正确推断为 HTMLButtonElement | HTMLAnchorElement 等。

拓展思考

  1. 性能:as 为自定义组件时,React 每次渲染都会执行 React.createElement(Component, ...),若 Component 是内联匿名函数会触发卸载/挂载,如何避免?
  2. 样式系统:在 CSS-in-JS(如 stitches、@mui/system)里,多态组件常与 styled 结合,需要把 as 转发到 styled 的 shouldForwardProp 黑名单,防止 as 出现在 DOM。
  3. 服务端渲染:Next.js 中若 as={Link},需把 passHref 自动注入,否则 SEO 失效;可再封装一层 <PolymorphicLink> 自动判断。
  4. 组合式 API:如果团队全面迁移到 React 19,可考虑用 use 与 Server Component`,把「多态」提升到 RSC 层,客户端只接收序列化后的「元素标签字符串」,从而减小包体。