Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

make tag more typesafe #73

Open
rexim opened this issue Jun 15, 2021 · 1 comment
Open

make tag more typesafe #73

rexim opened this issue Jun 15, 2021 · 1 comment

Comments

@rexim
Copy link
Member

rexim commented Jun 15, 2021

introduced in #72

Essentially get rid of the any

rexim added a commit that referenced this issue Jun 15, 2021
@weedz
Copy link

weedz commented Jan 4, 2022

Tag can extend the HTMLElement interface. Something like:

interface Tag extends HTMLElement {
    att$: (name: string, value: string) => Tag
    onclick$: (callback: (this: GlobalEventHandlers, ev: MouseEvent) => Tag) => Tag
}

A Tag can then be created with:

const result: Tag = Object.assign(document.createElement(name), {
    att$: function(name, value) {
        this.setAttribute(name, value);
        return this;
    } as Tag["att$"],
    onclick$: function(callback) {
        this.onclick = callback;
        return this;
    } as Tag["onclick$"]
});

The Object.assign() stuff might not be as clean as one would like. Another way to assign att$ and onclick$ to result would be:

const result = document.createElement(name);
(result as Tag).att$ = function(name, value) {
    this.setAttribute(name, value);
    return this;
};
(result as Tag).onclick$ = function(callback) {
    this.onclick = callback;
    return this;
};
// ...
return result as Tag;

And when Tag is no longer any we also need to properly cast the "mundane tags" to the appropriate element type:

function input(type: string) {
    return tag("input").att$("type", type) as Tag & HTMLInputElement;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants