Skip to content

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

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

Closed
soncodi opened this issue Nov 19, 2020 · 0 comments
Closed

Comments

@soncodi
Copy link

soncodi commented Nov 19, 2020

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:

microsoft/TypeScript#18194
microsoft/TypeScript#28551
#619

@soncodi soncodi closed this as completed Sep 1, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant