A factory function creates and returns an object or configured value for its caller. In JSX, the TypeScript compiler replaces each element with a call to a conventionally named createElement function, passing its tag, properties, and content. section 16.7.1
The compiler does not implement the factory’s behavior; the runtime supplies it. A custom createElement can use the DOM API to create HTMLElement objects, assign props, append text or nested elements, and return the result. section 16.7.3
A JSX factory handles two element forms:
- For a string tag such as div or button, it creates a DOM element, assigns the supplied properties, and appends children. section 16.7.3
- For a function or class tag, it creates an instance, assigns the supplied values to props, and calls getContent. section 16.7.3 section 16.8.1
- JSX properties use DOM property names, such as className rather than the HTML class attribute. section 16.7.1
Rendering a custom JSX component
A ProductList can render ProductItem and CategoryList elements with props containing products, categories, selected state, and callbacks. The factory creates each component, assigns its props, and incorporates the HTMLElement returned by getContent. section 16.8.1
Listing 16.27 The contents of the jsxFactory.ts file in the src/tools folder
export function createElement(tag: any, props: Object,
...children : Object[]) : HTMLElement {
function addChild(elem: HTMLElement, child: any) {
elem.appendChild(child instanceof Node ? child
: document.createTextNode(child.toString()));
}
if (typeof tag === "function") {
return Object.assign(new tag(), { props: props || {}}).getContent();
}
const elem = Object.assign(document.createElement(tag), props || {});
children.forEach(child => Array.isArray(child)
? child.forEach(c => addChild(elem, c)) : addChild(elem, child));
return elem;
}
declare global {
namespace JSX {
interface ElementAttributesProperty { props; }
}
}
The implementation shows the complete dispatch between DOM tags and component classes, including child handling and JSX props type-checking configuration. section 16.7.3










