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
)?
I think you should write your condinition based on nodeName
, hence it will return "#text" for text nodes.
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.