javascript - ¿No funciona typeof typeguard cuando se asigna a una variable?
Obtengo un error cuando uso un typeof como se muestra a continuación.
function func (variable: number | string) {
const is_number = (typeof variable === 'number');
let variable2: number,
variable3: string;
if (is_number)
variable2 = variable;
=> Type 'string | number' is not assignable to type 'number'.
Type 'string' is not assignable to type 'number'.
else
variable3 = variable;
=> Type 'string | number' is not assignable to type 'string'.
Type 'number' is not assignable to type 'string'.
}
Sin embargo, no hay un error como el siguiente.
function func (variable: number | string) {
let variable2: number,
variable3: string;
if (typeof variable === 'number')
variable2 = variable;
else
variable3 = variable;
}
URL para prueba
¿Siempre tengo que usarlo como arriba? ¿O hay alguna parte que he usado mal?
Gracias por leer :)
Respuesta #1
@Ry- ya respondió la pregunta real en los comentarios. A continuación hay una solución alternativa para la limitación.
Es POSIBLE hacer algo similar a lo que estás tratando de lograr con una función auxiliar a la que llamaré isNumber, que afirma si un argumento dado extends un cierto tipo en TypeScript. Esto proporciona una manera de no incluir en línea una afirmación de tipo del ámbito de JS como typeof variable === "number" después de todo. En su lugar, la afirmación ahora está contenida en una función.
Esto se hace usando la construcción x es y, que se llama un predicado de tipo (tendrás que desplazarte un poco hacia abajo). En el siguiente fragmento, el tipo de retorno de isNumber es un predicado de tipo de este tipo:
const isNumber = (subject: any): subject is number => {
return typeof subject === 'number';
};
Aquí, TypeScript puede inferir el tipo number a partir del booleano devuelto por isNumber. Ahora, si usas esta función auxiliar en tu propio func, todo debería estar bien:
function func (variable: number | string) {
let variable2: number;
let variable3: string;
if (isNumber(variable)) {
variable2 = variable;
} else {
variable3 = variable;
}
}
Dado que el bloque if solo se ejecutará si isNumber(variable) devuelve true, Typescript ahora asumirá que subject es number. El siguiente pseudocódigo demuestra cómo el código anterior debería ser interpretado por TS:
if (variable is number) {
// ...
}
También encontré esta respuesta en SO que explica más a fondo la construcción del predicado de tipo.
