First TypeScript program
Concept and syntax
Write the source in main.ts. A function names a reusable calculation: function double(n: number): number accepts a numeric parameter and promises a numeric return value. return sends the result to the caller. Compile with tsc --strict --target ES2022 --module commonjs --noEmitOnError main.ts and run node main.js. Use TypeScript 5.8.3 for this track; if it is not installed, install it in a new practice project with npm install --save-dev typescript@5.8.3 and replace tsc with npx tsc. Node runs the emitted JavaScript; this workflow does not depend on Node executing TypeScript directly.
Working example
Compile standalone examples in a fresh directory with tsc --strict --target ES2022 --module commonjs --noEmitOnError main.ts, then node main.js.
function double(n: number): number { return n * 2;}console.log(double(4), double(0));Expected output (one line per log):
8 0Common mistake
Intentionally invalid; check this snippet separately. Do not run it.
function double(n: number): number { return n * 2; }double("4");Expected compiler diagnostic: TS2345. A numeric-looking string is still a string. Pass the number 4 rather than the text "4".
Practice and recap
Write a triple(n: number): number function and test it with 5 and 0. Explain the role of each annotation.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
First TypeScript program — knowledge check
Check the concept, apply it to a new choice, and interpret a compiler diagnostic.
What does node main.js execute?
What does the final : number in the function header describe?
What change makes the call match the parameter contract?
function double(n: number): number { return n * 2; }double("4");