TypeScript-DOM-lib-generator
TypeScript-DOM-lib-generator copied to clipboard
I tried to make HTMLFormElement["method"] a stricter type by turning it into a union, but it doesn't seem to work?
According to the official HTML spec, the method attribute on a form element can be given one of three options, namely "get", "post", and "dialog".
Also, according to the spec, the method attribute is optional, in which case it defaults to "get". So in my opinion, the way the method attribute is typed in the DOM library in TypeScript (namely, as just a non-optional string) is wrong.
I think it should be typed like this: method?: "" | "get" | "post" | "dialog" | undefined. So I tried to accomplish that.
In inputfiles/overridingTypes.jsonc I added another property to "HTMLFormElement" for "method" and it looks like this:
"HTMLFormElement": {
"overrideIndexSignatures": [
"[index: number]: Element",
"[name: string]: any"
],
"properties": {
"property": {
"autocomplete": {
"name": "autocomplete",
"overrideType": "AutoFillBase"
},
"method": {
"name": "method",
"optional": true,
"overrideType": "\"\" | \"get\" | \"post\" | \"dialog\""
}
}
}
}
Anyhow, now that I changed it, when I run npm run build in my terminal, then I get generated/dom.generated.d.ts and it indeed modified the type of method as I had hoped:
/**
* Sets or retrieves how to send the form data to the server.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLFormElement/method)
*/
method?: "" | "get" | "post" | "dialog" | undefined;
This way, your IDE can give you auto-complete when writing the method attribute and it can warn you when you've typed a value that's not valid. I know that according to the spec, any invalid value will default back to "get", but if I accidentally filled in "postt", then I would like to receive a warning, instead of a silent failure.
Unfortunately however, TypeScript shows an error when I do this, saying that the type has to conform to the original HTMLFormElement type that's baked into Typescript.
Which is a little confusing to me. I mean, the whole point is to override the original type to improve it, isn't it? So what does this mean? Does it mean there's nothing really wrong and I should just ignore the error? Or does it mean I need to change something to make this work? Or does it mean that this simply can't be done?
Unfortunately however, TypeScript shows an error when I do this, saying that the type has to conform to the original HTMLFormElement type that's baked into Typescript.
You are seeing errors because you imported your lib-generator build output in parallel to your typescript.
With https://www.typescriptlang.org/tsconfig#lib you can omit the build-in DOM types and use only your new files.
I think creating a PR is fine with your changes.