Getting the type of element in a union 

The TypeScript inference system gets better with every version. In the most recent version, TypeScript uses a control flow to find out in a smart way the type depending on how the code is written. If a check is performed in one code path, TypeScript knows that for the closure of the type validation that the type is as checked. If an else code path exists to a type check, it knows that it is the reverse of the type comparison.

The following code example shows that depending on the position of the execution the type changes. It starts as a number or undefined. The value check against undefined makes the value narrow down to an undefined value for the scope of the if. The else can only be everything else than undefined in the union. In that particular case, it can only be a number. After if and else, TypeScript cannot know what the type is; thus, the value is back to both potential types:

function myFunction(value: number | undefined): void {
console.log("Value is number or undefined");
if (value === undefined) {
console.log("Value is undefined");
} else {
console.log("Value is NOT undefined, hence a number");
}
console.log("Value is number or undefined");
}

TypeScript understands the code flow. It is smart to freeze the type from a particular type check. In the following code example, a value equals to undefined force the function to return. It means that passing that point, there is no way to have an undefined value. The subtraction of undefined in the set of potential values diminishes the possibility to only a number:

function myFunction2(value: number | undefined): void {
console.log("Value is number or undefined");
if (value === undefined) {
return;
}
console.log("Value is NOT undefined, hence a number");
}

TypeScript narrows down the union from your conditional check for more than a primitive. You can also use this behavior with a discriminator and a user-defined type guard, which are two patterns that we will see in this chapter.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.14.39.59