Wednesday, January 22, 2025
HomeJavaScriptTypeScript: The issue with operate overloads | by Adrien Gautier | Jun,...

TypeScript: The issue with operate overloads | by Adrien Gautier | Jun, 2024


The principle purpose of the operate overloads is to situation the return sort in line with the enter parameters. We will obtain an analogous conduct with the conditional sort syntax as follows:

operate random<TMode extends "string" | "quantity">(
mode: TMode
): TMode extends "string" ? string : quantity {
if (mode === "string") {
return uuidv4();
}
return Math.random();
}

With the above syntax, we assert that:

  • the mode argument is both "string" or "quantity"
  • if the mode is "string" the return sort is string
  • else the return sort is quantity

Equally to operate overloads, the return sort is correctly inferred in line with the enter worth:

const randomString: string = random("string");

const randomNumber: quantity = random("quantity");

It handles unsure parameters…

In contrast to operate overloads, unsure enter values are allowed and propagates to the returned sort as anticipated:

const randomValue: string | quantity = random(mode as "string" | "quantity");

…however fails to constraint implementation

The excellent news sadly ends right here. With the intention to fulfill the conditional return sort, we truly have to introduce the sort any:

operate random<TMode extends "string" | "quantity">(
mode: TMode
): TMode extends "string" ? string : quantity {
if (mode === "string") {
return uuidv4() as any;
}
return Math.random() as any;
}

TypeScript is not capable of infer when a string should be returned or when a quantity should be returned. Worse, neither string nor quantityis assignable to the conditional return sort. The cleanest method I discovered is to make use of an alias like this:

sort Return<TMode extends "string" | "quantity"> = TMode extends "string"
? string
: quantity;

operate random<TMode extends "string" | "quantity">(
mode: TMode
): Return<TMode> {
if (mode === "string") {
return uuidv4() as Return<TMode>;
}
return Math.random() as Return<TMode>;
}

However even in that case, it will not forestall to return a string as a substitute of a quantity, and the opposite manner round.

Why TMode will not be narrowed down with the mode === "string" situation? It’s because we slim the sort related to an object, not the sort (alias) itself.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments