Promises in TypeScript
Promises in TypeScript — the core idea
A Promise represents a future result or rejection. A settled Promise has either fulfilled or rejected, never both. Attach a handler or use await to observe the result, and make sure rejection is handled.
What you’ll learn
- Explain promises in typescript with a concrete use case.
- Run the example and account for every line of its output.
- Recognize the difference between compile-time checking and runtime behavior.
Understand the rules and when to use them
Reading the code: The executor executes synchronously and resolves the Promise with 21. then registers a future callback. The synchronous scheduled log runs before the callback multiplies 21 by 2.
Keep the boundary clear: An unhandled rejection can be reported by the runtime; attach error handling to asynchronous operations that might fail.
See the idea as a flow
Run the complete TypeScript example
Save the code as promises.ts. The result below was captured after compiling this exact example with strict TypeScript checking and executing the emitted JavaScript in Node.js.
TypeScript code
const value = new Promise<number>(resolve => resolve(21));
value.then(number => console.log(number * 2));
console.log("scheduled");Verified output
scheduled
42Build: npx tsc --strict --target es2022 --module commonjs --lib es2022,dom,esnext.disposable promises.ts; run: node promises.js. The exact filename may be changed freely. When a multi-file project exists, prefer its tsconfig.json and build scripts.
Trace the example line by line
The executor executes synchronously and resolves the Promise with 21. then registers a future callback. The synchronous scheduled log runs before the callback multiplies 21 by 2.
The output shown above comes from the initialized values in this program. Replacing a type annotation alone does not transform a JavaScript value.
Avoid this common mistake
An unhandled rejection can be reported by the runtime; attach error handling to asynchronous operations that might fail.
Check both the TypeScript diagnostic and the emitted JavaScript behavior. A program can compile correctly and still need runtime validation or error handling.
Practice independently
Make a Promise<string> resolving with a greeting and use .then to print an uppercase version.
Before running your change, write down the type you expect TypeScript to infer and the output you expect JavaScript to print. Then check both predictions.
Check your understanding
What to remember
A Promise represents a future result or rejection.
Try the practice change and re-run the exact program to test your understanding.
Reaching the recap and completing the quizzes are separate milestones.