Thursday, March 23, 2023
HomeReactTypeScript: Sort Guards

TypeScript: Sort Guards


Sort Guards in TypeScript are wanted everytime you wish to permit solely a sure sort for a routine in TypeScript. On this TypeScript tutorial, you’ll learn to verify for person outlined sorts through the use of so-called user-defined sort guards.

We are going to begin with two sorts and two objects annotated respectively with these sorts:

sort Canine = {

identify: string;

age: quantity;

};

const trixi: Canine = {

identify: 'Trixi',

age: 49,

};

sort Individual = {

firstName: string;

lastName: string;

age: quantity;

};

const robin: Individual = {

firstName: 'Robin',

lastName: 'Wieruch',

age: 7,

};

On this TypeScript instance, we are going to get to our use case for sort guards by declaring a operate which will increase the age of every sort equally:

const celebrateBirthday = (mammal: Individual | Canine) => {

return {

...mammal,

age: mammal.age + 1,

};

};

console.log(celebrateBirthday(trixi).age);

console.log(celebrateBirthday(robin).age);

Nonetheless, earlier once we outlined the TypeScript annotated canine object, you already noticed that the Canine sort makes use of the age property otherwise in comparison with the Individual sort.

Drawback: Within the earlier instance, the canine is 49 years outdated in canine years and seven years outdated in human years. So naturally when celebrating a canine’s birthday, the age shouldn’t improve by 1 however by 7 once we sticking to expressing the age in canine years.

Person-Outlined Sort Guard

We are going to use a user-define sort guard to conditionally implement logic. Whereas the operate ought to improve the age by one for a Individual sort, the ought to improve it by seven for a Canine sort. In different phrases, based mostly on the argument’s sort of operate, it ought to conditionally apply logic.

const isDog = (mammal: Individual | Canine): mammal is Canine => {

return (mammal as Canine).identify !== undefined;

};

This new operate checks for a person outlined sort now. Whereas we permit passing in a Individual or Canine sort as object to this operate, the operate says that it should return an object of sort Canine through the use of a compelled sort assertion (additionally known as sort casting).

Inside this operate, to keep away from elevating any TypeScript errors, we solid the operate’s parameter to a Canine sort and verify that the identify property is just not undefined. As a result of in any case, solely objects of sort Canine have a identify property whereas objects of sort Individual have a firstName and lastName property.

Subsequent, use this person outlined sort guard as a operate name for the precise area logic:

const celebrateBirthday = (mammal: Individual | Canine) => {

return {

...mammal,

age: isDog(mammal) ? mammal.age + 7 : mammal.age + 1,

};

};

console.log(celebrateBirthday(trixi).age);

console.log(celebrateBirthday(robin).age);

And it really works. If the argument to this operate is of sort Canine, its age property will get elevated by seven. If it isn’t of sort Canine, then it solely will increase by one.

Final however not least, we wish to keep away from repetitive sort declarations, so we will extract these as union sort and reuse this new union sort at a number of locations:

sort Mammal = Individual | Canine;

const isDog = (mammal: Mammal): mammal is Canine => {

return (mammal as Canine).identify !== undefined;

};

const celebrateBirthday = (mammal: Mammal) => {

return {

...mammal,

age: isDog(mammal) ? mammal.age + 7 : mammal.age + 1,

};

};

Primarily that is the gist to protect in opposition to a a person outlined sort.

Bonus: In the event you solely wish to guard in opposition to a JavaScript primitive (e.g. quantity), simply checking for typeof (e.g. typeof mammal.age === 'quantity') is enough although. If the topic you wish to guard in opposition to is a JavaScript class (e.g. class Canine { ... }), you should use instanceof (e.g. canine instanceof Canine) as an alternative.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments