When an interface exposes a generic that simply get's used to type one the properties. Is there a way to "use" that based on inference at a usecase?
Take a look at this:
please assume here that the Generic cannot be simply applied, and that the
onClick
will exist.
As you can see, the is
property of my TestObject
is a generic, that is statically given. Is there a way to put bounds around this so when the onClick
wants an argument, it knows that the is
property is div
to therefore only allow value == 'div'
.
My use case for this is in the React world where I want my component to be given a prop that defines its render (createElement
), but need that to be typesafe for all handlers and attributes it applies. I suppose a generic would work, but that falls apart when sent into forwardRef
.
Here is an example of what I have currently, and also where my predicament lies.
import { AllHTMLAttributes, createElement, forwardRef } from 'react';
interface Props<Element extends keyof JSX.IntrinsicElements>
extends Omit<AllHTMLAttributes<Element>, 'width' | 'height'> {
is?: Element;
className?: string;
}
// There is a little more going on inside the Component, but you get the gist.
const Box = forwardRef<HTMLElement, Props<'div'>>(({ is, children }, ref) =>
createElement(is, {
ref,
}, children));
As you can see from there, now the is
prop is locked to just being a div
.