typescript - Varför behöver jag använda en typbestämning i min deklaration som tilldelar en variabel till null?


Jag är förbryllad över varför typen för variabeln a nedan inte är LoadStatus även om jag uttryckligen satte den i deklarationen:

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

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

Jag inspekterade typerna med Typescript-lekplatsen.

Svar #1

Detta är avsiktligt. Om det inte vore så, skulle mekanismer för olika typer vara betydligt mindre användbara. Till exempel:

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

Ett annat exempel skulle vara if-satser när man kontrollerar om det är null eller 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'
}

Redigera: Som @Boug påpekade beskrivs allt under inskränkning.

Svar #2

Detta kallas för att avgränsa unionstyp.

Kolla dokumentationen här så kommer du förstå varför det är som det är Docu

Följande exempel är mycket likt ditt snävnings exempel

Relaterade artiklar