In the realm of JavaScript, a function identified as async
consistently delivers a Promise
. This promise can be embraced with await
to fetch an internal value. (Discover more on MDN)
For instance.
async function getName() {
// Illustrative internals..
return "Celine";
}
const theNamePromise = getName();
// ^^ This is a Promise<string>
const theName = await getName();
// this is a string ("Celine")
Edit:
Tailored specifically for your illustration:
(Keep in mind, I don't have a definitive answer here. However, through some experimentation, I uncovered a few mildly intriguing discoveries. The following is a brief summary of my findings, and here is the example code I was playing with)
It's crucial to recognize that
Promise<string> | Promise<number>
and
Promise<string | number>
are similar but not entirely interchangeable from TypeScript's perspective.
To elaborate using an example, imagine if we applied your Result<T>
type similarly:
function getResult(): Result<string> | Result<number> {
// This return statement prompts a TS error
return {
data: Math.random() > 0.5 ? "test" : 5,
};
}
If you input this into TS, an error will arise because the returned value belongs to type { data: string | number; }
, not
{ data: string; } | { data: number; }
.
However, that type is compatible with Result<string | number>
function getResult2(): Result<string | number> {
// This is acceptable
return {
data: Math.random() ? "test" : 5,
};
}
This showcases a discrepancy in how TS interprets these types, yet it doesn't necessarily elucidate why the primary type returned by an async
can't be an amalgamation of two Promise<T>
types. Regrettably, I lack a comprehensive explanation there.