Skip to main content

    Lesson 1 • Beginner

    Introduction to TypeScript

    By the end of this lesson you'll understand what TypeScript is, why static types catch bugs before your code runs, how the tsc compiler turns TypeScript into JavaScript, and you'll have written your first typed variable.

    What You'll Learn

    • What TypeScript is and how it relates to JavaScript
    • Why static types catch bugs before your program runs
    • The concrete differences between TypeScript and JavaScript
    • How the tsc compiler turns TypeScript into JavaScript
    • How to install TypeScript and write your first .ts file
    • How to declare your first typed variable with an annotation

    💡 Real-World Analogy

    Think of TypeScript as the spell-checker and grammar-checker in a word processor. JavaScript lets you type anything and only notices a problem when someone reads the document out loud (at runtime). TypeScript underlines the mistake as you type — before anyone runs the program. The document you finally print is identical plain text either way; the checker just stops embarrassing errors from shipping. TypeScript checks your types the same way, then steps out of the way, leaving ordinary JavaScript to run.

    1. What Is TypeScript?

    TypeScript is an open-source language built and maintained by Microsoft. It is a superset of JavaScript — meaning every valid JavaScript program is already a valid TypeScript program. On top of plain JavaScript, TypeScript adds one big feature: static type checking. A "type" is just the kind of value something holds — text, a number, true/false — and "static" means TypeScript checks those kinds before the program runs, not while it's running.

    Because it's a superset, you can adopt TypeScript gradually. You don't rewrite anything; you rename a .js file to .ts and start adding type information wherever it helps.

    🔑 Key Concept

    TypeScript = JavaScript + Static Types. Any JavaScript you already know still works. TypeScript layers an optional, checkable description of your data on top — and then disappears, leaving plain JavaScript to actually run.

    2. Why Static Types Help

    JavaScript is dynamically typed: a variable can hold text now and a number a moment later, and nobody complains until the program actually trips over it at runtime — often in front of a user. That freedom is handy for tiny scripts but turns into hard-to-find bugs in real apps.

    Static types flip this around. You describe what each variable should hold, and TypeScript verifies it at compile time — before a single line runs. The payoff:

    • Bugs caught before runtime — a mistyped value is an error in your editor, not a 2am crash.
    • Better editor support — autocomplete, inline docs, and reliable rename/refactor.
    • Self-documenting code — a function's types tell you exactly what it expects and returns.
    • Safer refactoring — change one thing and the compiler points at every spot affected.
    • Scales to large codebases — teams can move fast without breaking each other's code.

    See the difference

    In JavaScript, this runs and silently produces nonsense — no error, just a bug:

    let total = 100;
    total = "free";          // JS allows it (no warning)
    console.log(total - 10); // NaN  — silent bug at runtime

    In TypeScript, the same mistake is stopped before the program runs:

    let total: number = 100;
    total = "free";   // ❌ TS2322: Type 'string' is not assignable to type 'number'
    // You fix it in your editor — it never reaches your users.

    3. TypeScript vs JavaScript

    They share the same syntax and run the same way in the end — TypeScript just adds a checking step first. Here's the side-by-side.

    FeatureJavaScriptTypeScript
    Type systemDynamic (checked at runtime)Static (checked at compile time)
    File extension.js.ts / .tsx
    Error detectionAt runtimeAt compile time + runtime
    Browser / NodeRuns directlyCompiled to JS first
    Learning curveLowerSlightly higher
    ToolingGoodExcellent (autocomplete, refactor)

    4. How tsc Compiles TS → JS

    Browsers and Node.js don't understand TypeScript — they only run JavaScript. So before you run anything, the TypeScript compiler (the tsc command) does two jobs: it checks your types, then erases them, leaving plain JavaScript. This erase step is why types cost you nothing at runtime — they vanish from the final code.

    # You write hello.ts
    let message: string = "Hi";
    
    # tsc checks the types, then strips them away...
    tsc hello.ts
    
    # ...producing hello.js with NO type annotations left:
    let message = "Hi";
    
    # Now any browser or Node can run it:
    node hello.js

    The example below is the actual JavaScript output of a typed program — the comments show the TypeScript you'd write, the code is what runs. Press Run to see the result.

    Worked example: your first program (compiled output)

    Read every comment, then run it. This is the JS that tsc produces from typed TS.

    Try it Yourself »
    JavaScript
    // This is plain JavaScript — exactly what TypeScript turns INTO.
    // In a real .ts file you'd write the type ": string" on the next line.
    // TypeScript checks the types, then erases them to produce this JS.
    
    function greet(name) {            // in TS: function greet(name: string): string
      return "Hello, " + name + "!";
    }
    
    let user = "World";              // in TS: let user: string = "World";
    console.log(greet(user));        // Hello, World!
    
    // The string above is fine. TypeScript would REJECT 
    ...

    5. Basic Setup

    TypeScript runs on Node.js. If you don't have it, install it from nodejs.org. Then add TypeScript to your project (the recommended way) and create a config file:

    # Start a project
    npm init -y
    
    # Add the TypeScript compiler as a dev dependency
    npm install --save-dev typescript
    
    # Generate a tsconfig.json with sensible defaults
    npx tsc --init
    
    # Compile every .ts file in the project
    npx tsc

    6. Your First Typed Variable

    A type annotation is the heart of TypeScript. You write the variable name, a colon, then the type: let age: number = 25;. The three types you'll use constantly are number, string, and boolean.

    // A TypeScript (.ts) file — the colon ": type" is the annotation
    let age: number = 25;        // a whole or decimal number
    let firstName: string = "Alice"; // text, in quotes
    let isActive: boolean = true;    // true or false
    
    // TypeScript can also INFER the type from the value, so this:
    let city = "London";   // city is automatically a string — no need to write it
    // is the same as: let city: string = "London";

    When the type is obvious from the value, you can skip the annotation and let type inference figure it out — you still get full safety. Now try it. The boxes below run as JavaScript (the comments show the matching TypeScript). Fill in each ___ and press Run.

    🎯 Your turn #1: declare two variables

    Replace the ___ blanks, then check your output against the expected lines.

    Try it Yourself »
    JavaScript
    // 🎯 YOUR TURN — replace each ___ then press "Run".
    // (This is runnable JS; in a .ts file you'd add ": number" / ": string".)
    
    // 1) Make a variable "age" holding a whole number, e.g. 30
    let age = ___;            // 👉 a number, no quotes  (in TS: let age: number = 30)
    
    // 2) Make a variable "city" holding some text
    let city = ___;           // 👉 text in "double quotes" (in TS: let city: string = "...")
    
    // These lines already work once your variables exist:
    console.log("You are " + age + " a
    ...

    One more. TypeScript's whole job is to keep a variable's type consistent — a number stays a number. Fill in two numbers so the calculation works:

    🎯 Your turn #2: keep the types consistent

    Fill in number values, then run the calculation.

    Try it Yourself »
    JavaScript
    // 🎯 YOUR TURN — TypeScript's job is to keep a value's TYPE consistent.
    // Fix the blanks so the maths actually works.
    
    let price = ___;          // 👉 a number like 9.99   (in TS: let price: number = 9.99)
    let quantity = ___;       // 👉 a number like 3       (in TS: let quantity: number = 3)
    
    let total = price * quantity;
    console.log("Total: $" + total.toFixed(2));
    
    // In a .ts file, writing  price = "free"  would be a COMPILE error
    // (TS2322: Type 'string' is not assignable to type 'number'
    ...

    Putting It Together: an Order Summary

    Here's a small, realistic program. Every variable would carry a type in a .ts file (shown in the comments), so a stray string in a number slot would be caught before it ever ran. Run it and tweak the numbers.

    Worked example: order summary

    Change the price and units and watch the subtotal update.

    Try it Yourself »
    JavaScript
    // === A tiny order summary — the kind of code TS keeps bug-free ===
    // In TypeScript each variable would carry a type annotation so that a
    // stray string in a number slot is caught BEFORE the program runs.
    
    let productName = "Mechanical Keyboard"; // in TS: : string
    let unitPrice = 79.99;                    // in TS: : number
    let units = 2;                            // in TS: : number
    let inStock = true;                       // in TS: : boolean
    
    let subtotal = unitPrice * units;         // 1
    ...

    Pro Tips

    • 💡 Let inference do the work: let n = 5; already makes n a number. Annotate when the type isn't obvious (function parameters, empty arrays).
    • 💡 Turn on "strict": true in tsconfig.json from day one — it's where most of the bug-catching power lives.
    • 💡 Use tsc --watch so the compiler recompiles automatically every time you save.
    • 💡 Adopt gradually: rename one .js file to .ts and add types where they pay off — you don't have to convert everything at once.

    Common Errors (and the fix)

    • "TS2322: Type 'string' is not assignable to type 'number'" — you put text where a number belongs, e.g. let n: number = "5";. Use a real number (5) or convert it with Number("5").
    • "TS2345: Argument of type 'string' is not assignable to parameter of type 'number'" — you passed the wrong type into a function. Pass the type the parameter expects.
    • Trying to run a .ts file directly: node hello.ts fails because Node runs JavaScript. Compile first with tsc hello.ts, then node hello.js (or use a runner like ts-node).
    • "Cannot find name 'tsc'": TypeScript isn't installed. Run npm install -g typescript, or use npx tsc inside a project.
    • "TS7006: Parameter 'x' implicitly has an 'any' type" — under strict mode you must annotate function parameters: function f(x: number) { ... }.

    📋 Quick Reference

    Command / ConceptWhat it does
    npm install -g typescriptInstall the compiler globally
    npx tsc --initCreate a tsconfig.json
    tsc hello.tsCompile one file to hello.js
    tsc --watchRecompile on every save
    let x: number = 1Annotate a variable's type
    : string / : booleanText type / true-false type
    .ts / .tsxTypeScript files (tsx = with JSX)

    Frequently Asked Questions

    Q: Do I have to rewrite my JavaScript to use TypeScript?

    No. Every .js file is already valid TypeScript. Rename it to .ts and add types only where they help. You can convert a project file by file.

    Q: Does TypeScript make my program run faster?

    No — the types are erased during compilation, so the JavaScript that runs is the same speed. The benefit is fewer bugs and better tooling while you write, not faster execution.

    Q: Why can't I just run a .ts file with node?

    Node and browsers only understand JavaScript. You compile first with tsc to get a .js file, then run that. Tools like ts-node bundle both steps for convenience.

    Q: Do I have to write a type on every single variable?

    No. TypeScript infers the type from the value, so let n = 5; is already typed as a number. Annotate when the type isn't obvious — function parameters are the most common case.

    Mini-Challenge: Profile Summary

    No blanks this time — just a brief and a starter outline. Declare the variables yourself, print the lines, and check your output against the example in the comments. (Write it as runnable JavaScript; the comments note the TypeScript type each variable would have.)

    🎯 Mini-Challenge: build a profile summary

    Declare the variables yourself and print a tidy summary.

    Try it Yourself »
    JavaScript
    // 🎯 MINI-CHALLENGE: Profile summary
    // (Write runnable JS here; imagine the TS type on each line.)
    //
    // 1. Make these variables:
    //      name      -> text     (in TS: : string)
    //      age       -> number   (in TS: : number)
    //      isStudent -> true/false (in TS: : boolean)
    // 2. Print three tidy lines using +  to join text and values.
    // 3. BONUS: print "Adult" if age is 18 or more, otherwise "Minor"
    //      (hint: age >= 18 ? "Adult" : "Minor")
    //
    // ✅ Example output:
    //    Name: Sam
    //   
    ...

    🎉 Lesson Complete

    • ✅ TypeScript is JavaScript plus static types — a superset, so your JS already works
    • ✅ Static types catch bugs at compile time, before your program ever runs
    • ✅ The tsc compiler checks then erases types, producing plain JavaScript
    • ✅ Set up with npm install --save-dev typescript and npx tsc --init
    • ✅ Declare a typed variable with an annotation: let age: number = 25;
    • Next lesson: Basic Types — explore every built-in type TypeScript gives you

    Sign up for free to track which lessons you've completed and get learning reminders.

    Cookie & Privacy Settings

    We use cookies to improve your experience, analyze traffic, and show personalized ads. You can manage your preferences below.

    By clicking "Accept All", you consent to our use of cookies for analytics and personalized advertising. You can customize your preferences or reject non-essential cookies.

    Privacy PolicyTerms of Service