Variable with many types

In many situations, a variable requires having more than one field. For example, you can have a field that only takes a value among a few strings:

type MyType = "a" | "b" | "c";
const m1: MyType = "a";
const m2: MyType = "no"; // Doesn’t compile

The creation of a type with the keyword type is not required but allows reusability of the type. The first example was creating a type with many allowed strings. A variable declared with the new type will only accept the strings from the list. However, most of the time, unions are using a more complex type, such as between the interface, type and primitive:

type AcceptedOption = number | string | { option1: string, option2: number };
const myOption1: AcceptedOption = "run";
const myOption2: AcceptedOption = 123;
const myOption3: AcceptedOption = { option1: "run", option2: 123 };

A function can take a union type as a parameter and return a return type as well. A union is often used to accept a type as well as undefined:

function functWithUnion(p: boolean | undefined): undefined | null{
return undefined;
}

When using a union, only the common fields are accessible. In the following code, TypeA has two fields, a and b, and TypeB has b and c. The only common field is b, which means that it is the only available and accessible field in the function. This is true until we narrow down the type to one of a type in the union. We will see how type narrowing works later:

interface TypeA {
a: string;
b: string;
}

interface TypeB {
b: string;
c: string;
}

function functionWithUnion(param1: TypeA | TypeB): void {
console.log(param1.b);
}
..................Content has been hidden....................

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