Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

179
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda