Equality narrowing
Apart from the typeof
operator we can also use other switch
statements and equality checks like ===
, !==
, ==
, and !=
to narrow types. For example:
ts
functionexample (x : string | number,y : string | null) {Property 'toUpperCase' does not exist on type 'string | number'. Property 'toUpperCase' does not exist on type 'number'.2339Property 'toUpperCase' does not exist on type 'string | number'. Property 'toUpperCase' does not exist on type 'number'.x .(); // Error toUpperCase 'y' is possibly 'null'.18047'y' is possibly 'null'.. y toUpperCase (); // Error// Butif (x ===y ) {// both are 'string' because that is the only type common to both// so we can use string methods without an errorx .toUpperCase ();y .toUpperCase (); // No Error}}
Since string
is the only type in common between the possible values of x
and y
, Typescript knows this and allows us to perform string operations.