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
)?
There are 12 node types.
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.
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.
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.
CharacterData (MDN)
Text (MDN)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With