Typescript: The type of TextNode

3.7k Views Asked by At

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)?

1

There are 1 best solutions below

1
webpreneur On BEST ANSWER

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)