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

175
Views
mecanografiado, verifique el tipo de objeto, tipo de obtener error de compilación

con este codigo

 export default class App { el: HTMLElement; constructor(el: string | HTMLElement) { if (typeof el === "string") { this.el = document.getElementById(el); } if (typeof el === typeof this.el) { this.el = el; } } }

obtener información de error de compilación:
Escriba 'cadena | HTMLElement' no se puede asignar al tipo 'HTMLElement'. El tipo 'cadena' no se puede asignar al tipo 'HTMLElement'.ts(2322)

código modificado como el siguiente, no obtendrá información de error:

 export default class App { el: HTMLElement; constructor(el: string | HTMLElement) { if (typeof el === "string") { this.el = document.getElementById(el); } if (el instanceof HTMLElement) { this.el = el; } } }

Estoy confundido, ambos deberían recibir un error o ambos deberían funcionar.

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

0

typeof puede devolver solo undefined , null , boolean , number , bigint , string , symbol , function y object .

Puede ver más detalles en este documento .

about 4 years ago · Juan Pablo Isaza Report

0

El error es claro, el tipo de typeof el devuelve uno de "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" tipo "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" en tiempo de ejecución.

En el momento del compilador de TS, typeof se convierte en un protector de tipo, TS reducirá el tipo a string | HTMLElement . Pero la instancia que this.el es solo HTMLElement .

Debe restringir el tipo de el a HTMLElement , por lo que debe verificar que no sea un tipo de string .

Las protecciones de tipo instanceof son una forma de restringir los tipos usando su función constructora.

la declaración el instanceof HTMLElement el tipo de el a HTMLElement que se puede asignar a this.el .

 class App { el: HTMLElement | null = null; constructor(el: string | HTMLElement) { if (typeof el === "string") { this.el = document.getElementById(el); } if (typeof el === typeof this.el && typeof el !== 'string') { this.el = el; } } }

Patio de juegos mecanografiado

about 4 years ago · Juan Pablo Isaza Report

0

Debe saber la diferencia entre el typeof de mecanografiado y el typeof de javascript. De acuerdo con este documento , cuando usa typeof en un contexto de expresión, en realidad está usando javascript. De este modo:

 if (typeof el === typeof this.el) { this.el = el; }

terminas comprobando dos entidades que tienen el tipo "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" . Para ayudar a mecanografiar a inferir el tipo correctamente, debe usar un tipo explícito en su condición:

 if (typeof el === 'object') { this.el = el; }

Pero en su caso, la mejor manera es usar una declaración else :

 if (typeof el === 'string') { this.el = document.getElementById(el); } else { this.el = el; }
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!