TypeScript - Basic Syntax

Hello there, future TypeScript wizards! ? I'm thrilled to be your guide on this exciting journey into the world of TypeScript. As someone who's been teaching programming for years, I can tell you that TypeScript is like a supercharged version of JavaScript, and it's going to make your coding life so much easier. Let's dive in!

TypeScript - Basic Syntax

Your First TypeScript Code

Alright, imagine you're about to write your first line in a new language. Exciting, right? Let's start with the classic "Hello, World!" program in TypeScript.

console.log("Hello, World!");

Now, you might be thinking, "Wait a minute, that looks just like JavaScript!" And you'd be right! TypeScript is a superset of JavaScript, which means all valid JavaScript is also valid TypeScript. But don't worry, we'll get to the cool TypeScript-specific stuff soon.

Let's try something a bit more TypeScript-y:

let message: string = "Hello, TypeScript!";
console.log(message);

Here's what's happening:

  • We're declaring a variable called message
  • The : string part tells TypeScript that this variable should only hold string values
  • We're assigning the string "Hello, TypeScript!" to this variable
  • Finally, we're printing it to the console

This is just a taste of TypeScript's type system, which is one of its most powerful features. It's like having a friendly robot assistant that catches your mistakes before you even run your code!

Compile and Execute a TypeScript Program

Now that we've written some TypeScript, how do we actually run it? Well, browsers and Node.js don't understand TypeScript directly, so we need to compile it to JavaScript first. It's like translating from TypeScript to a language that computers already know.

Here's how you do it:

  1. Save your TypeScript code in a file with a .ts extension, let's say hello.ts
  2. Open your terminal or command prompt
  3. Navigate to the directory containing your file
  4. Run the TypeScript compiler:
tsc hello.ts

This will create a new file called hello.js in the same directory. That's your TypeScript code translated to JavaScript!

To run it, you can use Node.js:

node hello.js

And voila! You should see your message printed in the console.

Compiler Flags

The TypeScript compiler is pretty smart, but sometimes you want to give it specific instructions. That's where compiler flags come in. They're like special commands you can give to the compiler to change how it behaves.

Here's a table of some common compiler flags:

Flag Description
--outDir Specifies an output folder for all emitted files
--target Specify ECMAScript target version
--watch Watch input files
--strict Enable all strict type-checking options

For example, if you want to compile your TypeScript to an older version of JavaScript for compatibility reasons, you could use:

tsc --target ES5 hello.ts

This tells the compiler to generate JavaScript that works with ECMAScript 5, which is supported by older browsers.

Identifiers in TypeScript

In programming, we use identifiers to name things like variables, functions, and classes. Think of them as labels for the different parts of your code. In TypeScript, there are some rules for these names:

  • They can contain letters, digits, underscores, and dollar signs
  • They must begin with a letter, underscore, or dollar sign
  • They are case-sensitive (so myVariable and MyVariable are different)
  • They can't be a reserved keyword (we'll talk about those next!)

Here are some valid identifiers:

let firstName: string = "John";
let _count: number = 5;
let $price: number = 9.99;
let camelCaseIsCommon: boolean = true;

And some invalid ones:

let 123abc: string = "Invalid"; // Can't start with a number
let my-variable: number = 10; // Can't use hyphens
let class: string = "Reserved keyword"; // Can't use reserved keywords

TypeScript ─ Keywords

Keywords are special words that have specific meanings in TypeScript. They're like the vocabulary of the language. You can't use them as identifiers because TypeScript has already given them a job to do.

Here's a table of some common TypeScript keywords:

Keyword Description
let Declares a block-scoped variable
const Declares a block-scoped constant
if Starts an if statement
for Starts a for loop
function Declares a function
class Declares a class
interface Declares an interface
type Declares a type alias

For example:

let x: number = 5;
const PI: number = 3.14159;

if (x > 0) {
    console.log("x is positive");
}

for (let i = 0; i < 5; i++) {
    console.log(i);
}

function greet(name: string): void {
    console.log(`Hello, ${name}!`);
}

class Person {
    name: string;
    constructor(name: string) {
        this.name = name;
    }
}

interface Shape {
    area(): number;
}

type Point = {
    x: number;
    y: number;
};

Each of these keywords has a specific purpose in structuring and defining your code.

Comments in TypeScript

Comments are like little notes you leave for yourself (or other developers) in your code. They're ignored by the compiler, so you can use them to explain what your code does without affecting how it runs.

TypeScript supports three types of comments:

  1. Single-line comments:

    // This is a single-line comment
    let x: number = 5; // You can also put them at the end of a line
  2. Multi-line comments:

    /* This is a multi-line comment
    It can span several lines
    Useful for longer explanations */
    let y: number = 10;
  3. Documentation comments:

    
    /**
  • This is a documentation comment
  • It's often used to generate documentation for functions or classes
  • @param name The name to greet
  • @returns A greeting message */ function greet(name: string): string { return Hello, ${name}!; }

Remember, good comments explain why you're doing something, not just what you're doing. The code itself should be clear enough to show what's happening.

TypeScript and Object Orientation

One of the great things about TypeScript is its support for object-oriented programming (OOP). If you're new to programming, think of OOP as a way of organizing your code around "objects" that have properties and behaviors.

Let's create a simple Car class to demonstrate:

class Car {
    // Properties
    make: string;
    model: string;
    year: number;

    // Constructor
    constructor(make: string, model: string, year: number) {
        this.make = make;
        this.model = model;
        this.year = year;
    }

    // Method
    describe(): string {
        return `This is a ${this.year} ${this.make} ${this.model}.`;
    }
}

// Creating an instance of Car
let myCar = new Car("Toyota", "Corolla", 2022);

console.log(myCar.describe()); // Outputs: This is a 2022 Toyota Corolla.

Let's break this down:

  • We define a Car class with properties for make, model, and year
  • The constructor is a special method that's called when we create a new Car
  • The describe method returns a string describing the car
  • We create a new Car object and call its describe method

TypeScript's type system really shines in OOP. It can catch errors like trying to assign a string to the year property, or calling a method that doesn't exist.

And there you have it! You've just taken your first steps into the world of TypeScript. Remember, learning to code is a journey, not a destination. Don't worry if everything doesn't click right away – keep practicing, keep experimenting, and most importantly, keep having fun! Before you know it, you'll be writing complex TypeScript applications and wondering how you ever lived without static typing. Happy coding! ?

Credits: Image by storyset