TypeScript-DOM-lib-generator icon indicating copy to clipboard operation
TypeScript-DOM-lib-generator copied to clipboard

ChildNode typings in lib.dom.d.ts for appendChild, insertBefore, others

Open soncodi opened this issue 4 years ago • 0 comments

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

soncodi avatar Nov 19 '20 06:11 soncodi