TypeScript-DOM-lib-generator
TypeScript-DOM-lib-generator copied to clipboard
ChildNode typings in lib.dom.d.ts for appendChild, insertBefore, others
Some methods on Node could have a stricter type. Currently, the typings contain:
// lib.dom.d.ts
interface Node extends EventTarget {
appendChild<T extends Node>(newChild: T): T;
insertBefore<T extends Node>(newChild: T, refChild: Node | null): T;
// ...
}
Which allows this code to typecheck:
document.body.appendChild(template.content.cloneNode(true)); // DocumentFragment ok
document.body.appendChild(new Document()); // throws
document.body.appendChild(document.createAttribute('x')); // throws
ChildNode mixes into CharacterData, Element, and DocumentType, per the spec, but not DocumentFragment. This leaves Document and Attr as the remaining types which extend Node, both of which are not ChildNodes. Also, ShadowRoot extends DocumentFragment but explicitly omitting it may complicate things.
I propose making similar typing changes relating to ChildNode here, too. Something like:
type InsertableNode = (Node & ChildNode)|DocumentFragment;
interface Node extends EventTarget {
appendChild<T extends InsertableNode>(newChild: T): T;
insertBefore<T extends InsertableNode>(newChild: T, refChild: Node | null): T;
// ...
}
I can send a PR if this change is appropriate.
Related Issues:
https://github.com/microsoft/TypeScript/issues/18194 https://github.com/microsoft/TypeScript/issues/28551 https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/619