新年好,請問如何解決這個問題 Typescript Playground
(已編輯 2023.01.24)
Google 了一會,修改了代碼,現在 props 可以根據 tagName 提示元素的屬性。這是修改前的代碼 (Typescript Playground)。但我還是卡在了 type 'string' can't be used to index type 'HTMLElement' 這個問題。
希望有人幫忙,十分感謝。
type ObjectProps = {
    style: Record<string, string> & Partial<CSSStyleDeclaration>
    dataset: Record<string, string | number | boolean>
}
type Props<K extends keyof HTMLElementTagNameMap> = Omit<HTMLElementTagNameMap[K], keyof ObjectProps>
function createElement<K extends keyof HTMLElementTagNameMap>(tagName: K, props: Partial<ObjectProps & Props<K>> = {}) {
    const elem = document.createElement(tagName);
    for (const [prop, value] of Object.entries(props)) {
        // type 'string' can't be used to index type 'HTMLElement'
        ["dataset", "style"].includes(prop) ? Object.assign(elem[prop], value) : elem[prop] = value;
    }
    return elem;
}
(已解決 2023.01.25)
抱歉我在嘗試 Typescript,應該多 Google 再發問。
function createElement<K extends keyof HTMLElementTagNameMap>(tagName: K, props: Partial<ObjectProps & Props<K>> = {}) {
    const element = document.createElement(tagName);
    type Prop = keyof typeof element;
    for (const [prop, value] of Object.entries(props)) {
        ["dataset", "style"].includes(prop) ? Object.assign(element[prop as Prop] as object, value) : element[prop as Prop] = value;
    }
    return element;
}