2

Quick question and I'm sure someone will have a quick answer for this one.

I am trying to use document.

document.createElement("button", "option");

typescript does not like this due to the second argument, it complains that it is only expecting one argument not two to be passed. In vanilla JS two arguments are acceptable.

How can I get the typescript compiler to allow this?

0

3 Answers 3

3

It does look like the standard definition does not allow for this, and seems to be wrong.

I guess a bug on github would be in order.

In the meantime as a hack you can save the function with another type. For example.

let createElement: (tagname: string, options: string) => HTMLElementTagNameMap = document.createElement;
Sign up to request clarification or add additional context in comments.

2 Comments

indeed, your solution is much better. :)
Still, the only related issue I found is #574. We could benefit from a new issue.
3

According to the standard, the second argument should be an object with a single is property, not a string. So, theoretically, that line should be:

document.createElement("button", { is: "option" });

The use of a string was part of an older spec and is deprecated, although supported by Chrome.

In any case, that overload is not in lib.d.ts, so you'll need to overload that definition yourself as @NitzanTomer describes, and/or create an issue at TypeScript's GitHub repo explaining the issue.

Note that the overload of createElement you are attempting to use is part of the Custom Elements spec, which as of this writing is a Working Draft, and thus the TypeScript maintainers would likely not support adding it to lib.d.ts.

Comments

2

It's missing from the definitions, but you can easily add it:

interface Document {
    createElement(tagName: string, options?: string | { is: string });
}

If you are using a module system (you import/export) then you need to do it like so:

declare global {
    interface Document {
        createElement(tagName: string, options?: string | { is: string });
    }
}

1 Comment

yes using the interface and declaring the options as optional has solved the issue, I'm a little embarrassed I didn't think of this myself but thank you so much @Nitzan you've really dug me out of a corner

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.