Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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" ...
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading