TypeScript

React.forwardRef & Generic

forwardRef 会导致丢失组件的 gerneric 入口
https://fettblog.eu/typescript-react-generic-forward-refs/
除 as 断言外,可以直接从顶部 declare forwardRef 实现自动提取 ref 到 props 类型中,并保留原组件的 generic 入口:

  1. // Redecalare forwardRef
  2. declare module "react" {
  3. function forwardRef<T, P = {}>(
  4. render: (props: P, ref: React.Ref<T>) => React.ReactElement | null
  5. ): (props: P & React.RefAttributes<T>) => React.ReactElement | null;
  6. }

原:

  1. type RefType = { ... }
  2. const ClickableList = React.forwardRef(ClickableListInner) as <T>(
  3. props: ClickableListProps<T> & { ref?: React.ForwardedRef<RefType> }
  4. ) => ReturnType<typeof ClickableListInner>;

不过独立组件依旧还是只能使用断言。