Structure of a TypeScript Program
Learn Structure of a TypeScript Program
A simple TypeScript file contains declarations and statements. It does not need a class or a mandatory main function.
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 structure of a typescript program.
- Predict the result of the complete runnable TypeScript example.
- Recognize one common mistake and correct it.
Understand the concept
A declaration introduces a name such as a constant or function. A statement performs an action; an expression produces a value. Functions can be invoked later, and top-level statements execute when the emitted JavaScript file is loaded.
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 rate: number = 5;
function multiply(value: number): number {
return value * rate;
}
const result = multiply(4);
console.log(result);Verified output
20How 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 rate constant is created. The function is declared; its body runs when multiply(4) is called. The returned 20 is assigned to result and printed.
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
A function declaration does not mean its body executes immediately. Look for the call site to understand program order.
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
Move the call below another console.log and observe which output appears first. Explain where function parameters get their values.
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
Structure of a TypeScript Program: A declaration introduces a name such as a constant or function.
Declaring a function defines behavior; invoking it executes the body.
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.