Files
ui-lib/lib/functions.ts
T
2026-11-24 08:27:04 +08:00

49 lines
1.3 KiB
TypeScript

import type { MarkRequired } from "./types";
export function createElement<K extends keyof HTMLElementTagNameMap>(
tagName: K,
init?: string | ((e: HTMLElementTagNameMap[K]) => void) | null,
...children: (string | Node)[]
): HTMLElementTagNameMap[K];
export function createElement(
tagName: string,
init?: string | ((e: HTMLElement) => void) | null,
...children: (string | Node)[]
): HTMLElement;
export function createElement(
tagName: string,
init?: string | ((e: any) => void) | null,
...children: (string | Node)[]
): HTMLElement {
const el = document.createElement(tagName);
if (typeof init === 'function') {
init(el);
} else if (init != null) {
el.className = init;
}
if (children.length > 0) {
el.append(...children);
}
return el;
}
export function mergeOptions<T extends object, D extends Partial<T>>(
defaults: D,
opts?: T
): MarkRequired<T, Extract<keyof D, keyof T>> {
const result: Record<string, unknown> = { ...defaults };
if (opts) {
for (const [key, value] of Object.entries(opts)) {
if (value !== undefined) {
result[key] = value;
}
}
}
return result as MarkRequired<T, Extract<keyof D, keyof T>>;
}