Narrowing type for function with a union in signatures

Complex functions can be hard to work with. This is often the case with a function with one or many parameters of different types, which can also return one or several types. TypeScript allows stitching any type together:

function f(p: number | string): boolean | Date {
if (typeof p === "number") {
return true;
}
return new Date();
}

const r1: boolean = f(1); // Does not compile
const r2: Date = f("string"); // Does not compile

In the previous code, the code is not compiling. The reason is because the function returns a union that must narrow down. However, if we add the overloads above the function, we can match the union to one particular set of parameters to a single return type. The previous code was not compiling because it was returning a union into a single type variable. With a change specifying that when a parameter is a number, then the function returns boolean, and when it is a string it returns a date, no casting or anything is required:

function f(p: number): boolean;
function f(p: string): Date;
function f(p: number | string): boolean | Date {
if (typeof p === "number") {
return true;
}
return new Date();
}

const r1: boolean = f(1);
const r2: Date = f("string");

This is beyond just associating a single parameter to a return type. For example, in the following code, we make sure we can only send all number parameters together or all strings together:

function g(p: number, q: number): boolean;
function g(p: string, q: string): Date;
function g(p: number | string, q: number | string): void {
}
g(1, "123"); // Doesn't compile
g(1, 2);
g("1", "2");
..................Content has been hidden....................

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