#Configuring JSX Namespace to Prioritize IntrinsicElements, Fallback to a Generic Element Type

5 messages · Page 1 of 1 (latest)

covert narwhal
#

I'm currently working on a custom JSX renderer detached from React or Preact or anything like that. I'm currently trying to setup both intrinsic elements while also supporting custom ones.

const testText = <text hi={true}>test</text>;
type TextType = typeof testText;

In Intellisense, hovering over <text> returns the correct (property) JSX.IntrinsicElements.text: CustomTextElement

However, the testText variable returns any when I would like it to either be CustomBaseElement or that same CustomTextElement

I've setup tsconfig.json to use my custom jsx.d.ts/jsx-runtime.ts

"jsx": "react-jsx",
"jsxImportSource": "mymodule",

I'm aware of setting the Element type in the JSX namespace

declare global {
  namespace JSX {
    interface IntrinsicElements {
      ...
      text: CustomTextElement;
      ...
    }
    type Element = CustomBaseElement; // <--- THIS
  }
}

and this does solve the problem, but it also turns the CustomTextElement <text> into a less-specific CustomBaseElement when I'm trying to achieve both -- that is, it'll prefer IntrinsicElements but otherwise use that CustomBaseElement instead of any (and type that testtext variable correctly)

Is this possible?

reef lily
#

@covert narwhal I don't think there's a way to get specific types out of JSX expressions.

#

React has the same issue: <div /> is typed as React.JSX.Element, not some more specific type that indicates that it's a div

covert narwhal
#

Gotcha - so you can't restrict elements passed as arguments to functions or as children - that's unfortunate, but thanks for confirming @reef lily - is there an issue around this I can follow?

covert narwhal
#
GitHub

TypeScript currently uses a JSX namespace to type the props of JSX elements. This is customisable by modifying JSX.IntrinsicElements, JSX.ElementClass. However, the type of an element is always JSX...

GitHub

React version: 18.2.0 Steps To Reproduce Create a JSX element of a functional component which has its props with type definitions Create another element of the same component using react's crea...