Typescript: The type of TextNode
Asked Answered
P

1

10

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

Paraguay answered 24/4, 2019 at 3:0 Comment(1)
great Q. surprised it (and the A) don't have a thousand up-votes.Epperson
S
5

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)

Swineherd answered 19/5, 2019 at 17:49 Comment(1)
But I didn't write the condition based on tagName. I wrote it based on nodeType. Anyway, you answered my question. Thanks.Paraguay

© 2022 - 2024 — McMap. All rights reserved.