Typescript: Suggestion: a precise return type of Node.appendChild()

Created on 4 Nov 2016  路  2Comments  路  Source: microsoft/TypeScript

TypeScript Version: 2.0.6

Code
From lib.es6.d.ts:

interface Node extends EventTarget {
  // ...
  appendChild(newChild: Node): Node;
  // ...
}

Test case:

document.createElement('div').appendChild(document.createElement('span'));

Expected behavior:
According to Node.appendChild() - MDN:

Syntax
var aChild = element.appendChild(aChild);
The returned value is the appended child.

The return type should be the type of the element being appended, in this case, HTMLSpanElement.

Actual behavior:
The appendChild(document.createElement('span')) just return with the type Node.

Suggestion
I wonder if it would be better using Generics to define the return type of appendChild(), such as:

interface Node extends EventTarget {
  appendChild<T>(newChild: T): T;
}
Bug lib.d.ts Fixed help wanted

Most helpful comment

interface Node extends EventTarget {
  appendChild<T extends Node>(newChild: T): T;
}

makes sense to me.

All 2 comments

interface Node extends EventTarget {
  appendChild<T extends Node>(newChild: T): T;
}

makes sense to me.

PRs welcomed. You can find more information about contributing lib.d.ts fixes at https://github.com/Microsoft/TypeScript/blob/master/CONTRIBUTING.md#contributing-libdts-fixes.

Was this page helpful?
0 / 5 - 0 ratings