Skip to content

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

Closed
@soncodi

Description

@soncodi

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions