From babc485209737342df3966d5e134f79ba949edce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rafa=C5=82=20Ca=C5=82ka?= Date: Fri, 22 Sep 2023 20:41:30 +0200 Subject: [PATCH] refactor: Modularize type definitions for createElement options --- src/createElement.ts | 39 +++++++++++++++++++-------------------- 1 file changed, 19 insertions(+), 20 deletions(-) diff --git a/src/createElement.ts b/src/createElement.ts index d0ba508..9ade002 100644 --- a/src/createElement.ts +++ b/src/createElement.ts @@ -22,8 +22,7 @@ */ export default function createElement( tagName: K, - options: Partial> & - SpecialAttributes = {}, + options: CreateElementOptions = {}, target = document, ): HTMLElementTagNameMap[K] { const element = target.createElement(tagName); @@ -34,36 +33,36 @@ export default function createElement( } else { element.classList.add(value as string); } - return; - } - - if (key === 'dataset' && typeof value === 'object' && value !== null) { + } else if ( + key === 'dataset' && + typeof value === 'object' && + value !== null + ) { Object.entries(value as Record).forEach( ([dataKey, dataValue]) => { element.dataset[dataKey] = dataValue; }, ); - return; - } - - if (key === 'text') { + } else if (key === 'text') { element.textContent = value as string; return; - } - - if (key in element) { + } else if (key in element) { (element as any)[key] = value; return; + } else { + element.setAttribute(key, value as string); } - - element.setAttribute(key, value as string); }); return element; } -export type SpecialAttributes = Partial<{ - class: string | string[]; - dataset: Record; - text: string; -}>; +type SpecialAttributes = { + class?: string | string[]; + dataset?: Record; + text?: string; +}; + +export type CreateElementOptions = + (Partial> & + SpecialAttributes) & { [key: string]: any };