I've been diving into typescript and transitioning my current code to use it.
In the code snippet below, my goal is:
- Retrieve selection
- Get anchorNode from selection -> which is of type 'Node'
- If anchorNode has attributes, retrieve attribute data
The issue arises when I try to access anchorNode, as it is typed as "Node" without an "attributes" property.
However, the anchorNode actually does have an attribute property that I need to access.
I'm looking for a way to resolve this TypeScript error. The HTMLElement type contains attributes, but I am unsure how to connect or extend the Node type with the HTMLElement type.
Any advice would be greatly appreciated.
//...
const windowSelection = window.getSelection();
const anchorNode = windowSelection?.anchorNode
// TypeScript error: Property 'attributes' does not exist on type 'Node'
if (anchorNode && anchorNode.attributes) {
const dataOffsetKey = anchorNode?.attributes['data-offset-key']?.value;
// perform actions using dataOffsetKey
}
//...
Thanks to @CertainPerformance
I was able to resolve the TypeScript error mentioned above, but then encountered the error
element implicitly has an ‘any’ type because index expression is not of type ‘number’.
This led me to the following solution.
const dataOffsetKey = (anchorNode.attributes as { [key: string]: any })[ 'data-offset-key' ]?.value;
I find this approach somewhat cumbersome. Are there any recommended solutions for this?