-
Notifications
You must be signed in to change notification settings - Fork 12.7k
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
Strongly-typed DOM access #5792
Comments
I would say the ideal solution here, is if you had a some "tool" that would inspect your .html files, and generate a .d.ts file to match them, so in your case, you would generate an overload to interface Document {
getElementById(elementId: "myElement"): HTMLTextAreaElement;
} now for your use case, i do not see any issue with defining your additional overload: interface Document {
getElementById<T>(elementId: string): T;
getElementById(elementId: string): HTMLElement; // general
} |
You may want a type provider feature suggested by #3136. |
Mohamed - would you be willing to take a PR for generic versions of the @saschanaz I think a Type Provider is precisely what is required. A more formalized mechanism to implement Mohamed's tool idea within the context of the language. |
I wrote a little spike to inventory HTML files: https://github.com/nycdotnet/html-to-ts-definition/ I suppose this would be a good way to achieve the automatic strongly-typed functionality. I will submit a PR for the generic I'll close this in favor of #3136. |
If I have a
textarea
element on my HTML page, the following JavaScript works:However to get this to work in TypeScript, I'm currently forced to use parentheses like this:
This is not only ugly, but the extra parentheses remain in the transpiled JS.
It'd be great if getElementById had a generic form in lib.d.ts such as:
This would allow the much cleaner-looking TypeScript code that also doesn't affect the emit:
To be honest, though, even with this change, it'd be nice if there were a switch that would bypass property missing errors on HTMLElement. That would remove a significant amount of day-1 work for folks transitioning to TypeScript.
Perhaps something like making the non-generic
getElementById
return aHTMLGeneralizedElement
which would extendHTMLElement
and add common properties likevalue
andchecked
asany
. This would cover the scenario "I want to try TypeScript for my currently-working web page, but not resolve dozens of non-errors first", but not impact those who want to strongly-type everything (they'd just use the generic version).The text was updated successfully, but these errors were encountered: