Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

288
Views
La propiedad {creada en el elemento html} no existe en el tipo 'HTMLElement'

En mecanografiado, un elemento html se escribe con HTMLElement. Pero, ¿qué sucede si agrego una propiedad a ese elemento HTML? El tipo HTMLElement fallará. ¿Cómo puedo escribir un elemento html con una nueva propiedad? Aquí está el código donde me sale el error:

 function divModify():HTMLElement{ const div:HTMLElement= document.createElement("div"); div.id= "test"; div.classList.add("d-flex"); const info={text: "Hello word"} Object.defineProperty(div,"info",{value:info}) console.log(div) console.log(div.info) return div } divModify()

el error:

La propiedad 'info' no existe en el tipo 'HTMLElement'.

y un patio de recreo del código: patio de recreo del código

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Si bien el analizador de flujo de TypeScript es muy impresionante y permite refinar, reducir o ampliar los tipos dentro de un alcance cuando usa protector de tipo type predicate functions , typeof e instanceof , TypeScript aún no realiza un seguimiento de todos los cambios en el tipo de una variable que, de otro modo, deberían poder deducirse del uso del operador in u Object.defineProperty .

(ACTUALIZACIÓN: Entonces TypeScript 4+ se usa in estrechar , pero solo para discriminar entre posibilidades en tipos de unión)

... así que hasta que TypeScript admita el seguimiento Object.defineProperty , puede solucionar esa limitación con algunos ajustes manuales:

  • Definición manual de un nuevo type que combina el tipo HTMLDivElement integrado del DOM con una info: { readonly text: string } tipo.

    • Mi código a continuación también define el tipo de info como type MyInfo en lugar de ser anónimo.
    • Llamo a esto HTMLDivElementWithInfo .
  • Cambie la función divModify para devolver HTMLDivElementWithInfo en lugar de HTMLDivElement .

  • Agregue una aserción de tipo al valor de retorno de Object.defineProperty (que es un alias de div ) llamado div2 como HTMLDivElementWithInfo .

  • Después de todo eso, tsc ahora le permitirá desreferenciar div.info .

Al igual que:

Enlace del patio de recreo .

 type MyInfo = { readonly text: string; }; type HTMLDivElementWithInfo = HTMLDivElement & { info: MyInfo }; function createDivWithInfo(): HTMLDivElementWithInfo { const div = document.createElement("div"); div.id = "test"; div.classList.add("d-flex"); const initialInfoPropValue = { text: "Hello word" }; const div2 = Object.defineProperty( div, "info", { value: initialInfoPropValue } ) as HTMLDivElementWithInfo; console.log( div2 ); console.log( div2.info ); return div2; } const d = createDivWithInfo(); console.log( d.info );
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!