Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: The type of TextNode

If you write below code:

const e = document.body.firstChild;
if (e.nodeType === Node.TEXT_NODE)
    console.log(e.data);

You will get this error on e.data:

TS2339: Property 'data' does not exist on type 'ChildNode'.

While if the condition be true (e.nodeType === Node.TEXT_NODE) then e has some other properties in addition to regular ChildNode properties, like data and wholeText.


What type should I cast to (other than any)?

like image 381
Mir-Ismaili Avatar asked Apr 24 '19 03:04

Mir-Ismaili


People also ask

How many types of DOM nodes are there?

There are 12 node types.

What is a TextNode?

A text node encapsulates XML character content. A text node can have zero or one parent. The content of a text node can be empty. However, unless the parent of a text node is empty, the content of the text node cannot be an empty string.

What is the node type?

A node type is a collection of an application's nodes that share a common business purpose. Use node types to define nodes' properties and to define rules that convert a node type to another node type. Each node is a member of a node type.


1 Answers

I think you should write your condinition based on nodeName, hence it will return "#text" for text nodes.

nodeName Example on MDN

The interface what you are looking for in TypeScript is CharacterData or simply Text. On the Text interface you will have both the data and wholeText properties since it implements the characterData interface. On the characterData abstract interface you only have the data prop.

Character​Data (MDN)

Text (MDN)

like image 80
webpreneur Avatar answered Sep 22 '22 07:09

webpreneur