Búsqueda de sitios web

typescript - ¿Por qué necesito usar una aserción de tipo en mi declaración que asigna una variable a null?


Estoy desconcertado por qué el tipo de la variable a a continuación no es LoadStatus aunque lo puse explícitamente en la declaración:

type LoadStatus = 'succeess'|'failure'|null;

let a: LoadStatus = null;
let b = null as LoadStatus;
a; // type is null
b; // type is LoadStatus

Inspeccioné los tipos usando el playground de Typescript.

Respuesta #1

Esto es intencional. Si no fuera así, los mecanismos de tipo diversos serían significativamente menos útiles. Por ejemplo:

type LoadStatus = 'success' | 'failure' | null;

let a: LoadStatus = null;
let b = null as LoadStatus;
a ; // type is null

b; // type is LoadStatus

// null is converted to 'failure', so that always a string is returned
type ConvertLoadStatus<T extends LoadStatus> = T extends null ? 'failure' : T;

type resultA = ConvertLoadStatus<typeof a>; // failure;
type resultB = ConvertLoadStatus<typeof b>; // 'success' | 'failure', not very helpful

a = 5; // a is still not assignable to other things than described, so typing still protects the variable

Otro ejemplo serían las sentencias if al comprobar si es null o undefined:

type ExampleType = {a: string, b: number} | null;

function doSomething(a: ExampleType) {
  if(a != null) {
    a // a is {a: string, b: number}
    a.a // a can now be accessed
    // How would we ever be able to access a if it always stayed ExampleType?
  }
  a.a // Object is possibly 'null'
}

Editar: Como señaló @Boug, todo está descrito bajo el concepto de restricción.

Respuesta #2

Esto se llama estrechamiento del tipo unión.

Consulta la documentación aquí y entenderás por qué es como es Docu

El siguiente ejemplo es muy parecido a tu ejemplo de estrechamiento

Artículos relacionados