Typescript -extend interface Node=HTMLElement

I am using Cypress 10.
I have seen this code:

 Cypress.Commands.add(
  'byTestId',
  // Borrow the signature from cy.get
  <E extends Node = HTMLElement>(
    id: string,
    options?: Partial<
      Cypress.Loggable & Cypress.Timeoutable & Cypress.Withinable & Cypress.Shadow
    >,
  ): Cypress.Chainable<JQuery<E>> =
    cy.get(`[data-testid="${id}"]`, options),
);

What does the E extends Node = HTMLElement means exactly? and can it be replaced by E extends HTMLElement
Is there a difference in these two?

>Solution :

E extends Node = HTMLElement is a generic type parameter with a constraint of Node, and if it can’t be inferred by the TypeScript compiler, it will default to HTMLElement.

For Node vs HTMLElement, you may want to see this question:

A node is the generic name for any type of object in the DOM hierarchy. A node could be one of the built-in DOM elements such as document or document.body, it could be an HTML tag specified in the HTML such as <input> or <p> or it could be a text node that is created by the system to hold a block of text inside another element. So, in a nutshell, a node is any DOM object.

An element is one specific type of node as there are many other types of nodes (text nodes, comment nodes, document nodes, etc…).

Leave a Reply