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.
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
instanceofson 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; } } }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; }