Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

212
Views
How to appropriately type a component which forwards an _arbitrary_ ref?

So I want to have a component which takes an as prop, and from that creates an element. In code, this is simple enough:

function Box({ as = 'div', children, ...props }) {
  return createElement(as, props, children);
}

I can derive the props for a given as using the following basic code:

type Elements = JSX.IntrinsicElements;
type ElementType = keyof Elements | ComponentType<any>;

type ElementProps<TElement> = TElement extends keyof Elements
  ? Elements[TElement]
  : TElement extends ComponentType<infer TProps>
  ? TProps
  : never;

type Props<TElement> = {
  readonly as: TElement;
} & ElementProps<TElement>;

type DivProps = Props<{as: 'div'}>; // this works

However, what I'm having problems with is forwarding the ref.

I can do the following to convert the literal string into an HTMLElement

type InferElement<TElement> = TElement extends keyof HTMLElementTagNameMap
  ? HTMLElementTagNameMap[TElement]
  : TElement;

type DivElement = InferElement<'div'>; // HTMLDivElement

But I can't seem to get it to work when forwarding the ref:

function BaseBox<T extends ElementType>(
  { as = 'div', children, ...props }: Props<T>,
  ref: ForwardedRef<InferElement<T>>
) {
  return createElement(as, props, children);
}

const Box = forwardRef(BaseBox); // this doesn't work

How would I go about telling typescript how to interpret this correctly?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!