Typing Promises
Asynchronous functions structurally operate identically natively inside both JavaScript and TypeScript (utilizing the native Event Loop mechanism securely behind the scenes).
However, typing the specific resolved data configuration stemming from the asynchronous delay is arguably exclusively unique securely to TypeScript interfaces natively.
The Promise<T> Generic
Any async function must structurally specify that it returns a Promise. Furthermore uniformly, you must map explicitly utilizing a Generic what exact shape the final unboxed data configures natively into.
// Define our strict Interface shape securely
interface UserAccount {
id: number;
username: string;
}
// Ensure the outer function safely returns a Generic mapped Promise configuration!
async function fetchUser(userId: number): Promise<UserAccount> {
const rawData = await fetch(`https://api.example.com/users/${userId}`);
const parsedData: UserAccount = await rawData.json();
return parsedData;
}
If you construct an async function internally that solely computes data entirely in the background completely avoiding returning any explicit variables perfectly, you safely map Promise<void>.
async function pingServer(): Promise<void> {
await fetch('https://api.example.com/ping');
console.log("Server pinged successfully.");
}