TypeScript Input and Output
Learn TypeScript Input and Output
Programs receive values from their environment and send results back. The mechanism depends on whether JavaScript runs in a browser or Node.js.
In this lesson, you will study the rule, run a complete TypeScript example, explain its output, and test a small change.
What you’ll learn
- Explain the main rule behind typescript input and output.
- Predict the result of the complete runnable TypeScript example.
- Recognize one common mistake and correct it.
Understand the concept
console.log writes output in both browser and Node consoles. Browser prompt can gather text but is not available in ordinary Node programs. Node terminal input uses APIs such as readline, covered later. User input arrives as runtime data; even if a TypeScript variable has a declared type, parsing and validation remain necessary.
See the concept visually
Use the diagram to locate the checks, values or branches involved in the example.
Run a complete TypeScript example
Save this code as main.ts or paste it into the TypeScript Playground. The example uses fixed values so it runs without prompting for input.
TypeScript code
const rawInput: string = "25"; // Imagine text entered by a user.
const age = Number(rawInput);
if (Number.isFinite(age)) {
console.log(`Next year: ${age + 1}`);
} else {
console.log("Invalid number");
}Verified output
Next year: 26How to run locally: npx tsc --strict --target es2022 --module commonjs main.ts, then node main.js. When using a project configuration, run the matching project build instead.
Trace the execution
The example deliberately stores sample text rather than reading stdin, so it runs in any basic TypeScript environment. Number parses it to 25 and the program prints 26.
Predict the output before you run the sample. Compare each line with the source expression that produced it, and distinguish the type checker’s work from what happens in JavaScript at runtime.
Common mistakes and how to avoid them
Avoid calling Number on arbitrary text without checking the result, and remember that Number("") equals 0 rather than indicating missing input.
Debugging habit: when a change is rejected, read the exact compiler diagnostic and inspect the operand types. When it compiles but behaves unexpectedly, follow the values through the JavaScript expressions.
Practice it yourself
Change rawInput to "hello" and observe the invalid-number branch. Then try whitespace and decide how real input should treat it.
Challenge: write down your prediction first, run the changed source, and explain any difference. Return to the verified version before continuing.
Check your understanding
Review the key idea
TypeScript Input and Output: console.
TypeScript types do not replace runtime parsing and validation.
Before continuing, be able to explain what is checked before execution and what actually changes at runtime in the example above.
Reaching the recap and completing the quizzes are separate milestones.