TypeScript Type for HTML Element Tag


I am working on a TypeScript + React project. For a component, I want to use the polymorphic as prop. However, I want to restrict it to HTML tags so it will not accept ReactNodes or JSX Elements. But I do not know which type I can use to achieve this.

<Foo as="section">...</Foo> ✅
<Foo as={SomeOtherComponent}>...</Foo> ❌

I have tried using React.ElementType but that still looks to accept other components.

interface Foo {
  as?: React.ElementType

Which type could I use to accept only HTML tags but not other elements or nodes?


You could accept only a string, not a function:

interface Foo {
    as?: string;

Or you could more specifically accept only known HTML tag names using a string literal union; you don’t have to write out the names yourself, you can get them from HTMLElementTagNameMap in lib.dom.d.ts:

interface Foo {
    as?: keyof HTMLElementTagNameMap; // This is "a" | "abbr" | "address" ...

Answered By – T.J. Crowder

Answer Checked By – Katrina (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.