Skip to content

NamedNodeMap/getNamedItem is not defined to be potentially "null" #17695

Closed
@DorianGrey

Description

@DorianGrey

TypeScript Version: 2.4.2

I've recently faced in issue accessing the NamedNodeMap of a Node - a user managed to insert an img tag without a src attribute. My code accessed attributes.getNamedItem("src") on the node, and (accidentially) did not check if the resulting attr exists before accessing its .value, and the function crashed with a type error.
While not performing this check is my personal mistake, I've figured out that getNamedItem is not defined to possibly return null: https://github.com/Microsoft/TypeScript/blob/master/lib/lib.es6.d.ts#L14075

However, this function will return null in case the attributes does not exist:
https://developer.mozilla.org/en-US/docs/Web/API/NamedNodeMap/getNamedItem
This should hold true for getNamedItemNS as well.

Thus, as I've strict resp. strictNullChecks enabled in in my tsconfig.json, the compiler should raise in error when not checking the result for null (see code below).

Code

const node: Node = // ... an <img> node
const src: Attr = this.attributes.getNamedItem("src"); // should complain that src should be of type Attr | null
const valueLength = src.value.length; // should complain that src might be null.

Expected behavior:
The code mentioned above compiles without an error that src might be null, even with the config strict resp. strictNullChecks enabled. It does because the definition mentions that the result of getNamedItem is always an Attr.

Actual behavior:
The code mentioned above should raise a compiler error in case strict resp. strictNullChecks is enabled. The definition should mention that the result of getNamedItem is of type Attr | null.

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugA bug in TypeScriptDomain: lib.d.tsThe issue relates to the different libraries shipped with TypeScriptFixedA PR has been merged for this issueHelp WantedYou can do this

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions