Extending Types

Estimated reading time: 2 minutes

Kita Html's type system can be extended to support custom elements, custom attributes, or both.

Custom elements

Declare new entries in JSX.IntrinsicElements to add custom HTML elements with typed attributes.

declare global {
  namespace JSX {
    interface 
interface JSX.IntrinsicElements
IntrinsicElements
{
'user-card':
interface JSX.HtmlTag
HtmlTag
& {
'user-id': number
children: string
children
: string
} } } } const
const html: JSX.Element
html
= <
JSX.IntrinsicElements['user-card']: JSX.HtmlTag & {
    'user-id': number;
    children: string;
}
user-card
'user-id': number
user-id
={42}>Arthur</
JSX.IntrinsicElements['user-card']: JSX.HtmlTag & {
    'user-id': number;
    children: string;
}
user-card
>
<user-card user-id="42">Arthur</user-card>
Capitalized tags are components

JSX interprets capitalized tags as components. Use lowercase custom element names for intrinsic elements. When the tag name cannot be written directly in JSX, use <tag of="..."> instead.

declare global {
  namespace JSX {
    interface 
interface JSX.IntrinsicElements
IntrinsicElements
{
JSX.IntrinsicElements.Example: HtmlTag
Example
:
interface JSX.HtmlTag
HtmlTag
} } } const
const html: JSX.Element
html
= <Example />
Cannot find name 'Example'.

Custom attributes on all elements

Extend the HtmlTag interface to add attributes to every native HTML element.

declare global {
  namespace JSX {
    interface 
interface JSX.HtmlTag
HtmlTag
{
'data-testid'?: string } } } const
const html: JSX.Element
html
= <
JSX.IntrinsicElements.div: JSX.HtmlTag
div
JSX.HtmlTag['data-testid']?: string | undefined
data-testid
="header">content</
JSX.IntrinsicElements.div: JSX.HtmlTag
div
>
<div data-testid="header">content</div>

Allow any tag and attribute

If you need to bypass type checking entirely, add a triple-slash directive to your src/kita.d.ts file. This is not recommended for production code.

Without the unrestricted type extension, unknown tags are rejected:

const 
const html: JSX.Element
html
= <myrandomtag myrandom-attribute="value" />
Property 'myrandomtag' does not exist on type 'JSX.IntrinsicElements'.

Add @kitajs/html/all-types to allow any tag and attribute:

/// <reference types="@kitajs/html/all-types" />

const 
const html: JSX.Element
html
= <
IntrinsicElements[string]: any
myrandomtag
myrandom-attribute: string
myrandom-attribute
="value" />
<myrandomtag myrandom-attribute="value"></myrandomtag>