</>
Skip to content
TypeScript lessons (4/31)

TypeScript — Syntax

Variables

// let: block-scoped, mutable
let count = 0;
count = 10;

// const: block-scoped, immutable binding
const PI = 3.14159;
// PI = 3; // Error: cannot reassign

// var: function-scoped (avoid)
var oldWay = "don't use";

Type annotations

// Explicit types
let name: string = "Alice";
let age: number = 30;
let isActive: boolean = true;
let nothing: null = null;
let notDefined: undefined = undefined;

// Type inference (let TypeScript figure it out)
let inferred = "hello"; // string
let num = 42;           // number

Functions

// Function declaration
function greet(name: string): string {
    return `Hello, ${name}!`;
}

// Arrow function
const add = (a: number, b: number): number => a + b;

// Optional parameters
function log(message: string, level?: string): void {
    console.log(`[${level ?? "INFO"}] ${message}`);
}

// Default parameters
function multiply(a: number, b: number = 2): number {
    return a * b;
}

// Rest parameters
function sum(...numbers: number[]): number {
    return numbers.reduce((total, n) => total + n, 0);
}

Objects

// Object type annotation
const person: { name: string; age: number } = {
    name: "Alice",
    age: 30
};

// Shorthand property
const x = 10, y = 20;
const point = { x, y }; // { x: 10, y: 20 }

// Computed property names
const key = "name";
const obj = { [key]: "Alice" };

Arrays

// Type annotation
let nums: number[] = [1, 2, 3];
let names: Array<string> = ["Alice", "Bob"];

// Readonly arrays
const readonly: readonly number[] = [1, 2, 3];
// readonly.push(4); // Error

// Tuple
let tuple: [string, number] = ["Alice", 30];
// tuple = [30, "Alice"]; // Error: wrong order

Template literals

const name = "Alice";
const age = 30;

// String interpolation
const greeting = `Hello, ${name}!`;

// Expression interpolation
const msg = `${name} is ${age + 1} next year`;

// Tagged templates
function highlight(strings: TemplateStringsArray, ...values: unknown[]) {
    return strings.reduce((result, str, i) => {
        const value = values[i] ?? "";
        return result + str + `<b>${value}</b>`;
    }, "");
}

const html = highlight`Hello, ${name}!`;

Control flow

// if/else
if (age >= 18) {
    console.log("Adult");
} else {
    console.log("Minor");
}

// Ternary
const status = age >= 18 ? "Adult" : "Minor";

// switch
switch (true) {
    case age < 13:
        console.log("Child");
        break;
    case age < 18:
        console.log("Teenager");
        break;
    default:
        console.log("Adult");
}

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

// for...of
for (const name of ["Alice", "Bob"]) {
    console.log(name);
}

// for...in
for (const key in { a: 1, b: 2 }) {
    console.log(key);
}

Destructuring

// Object destructuring
const { name: n, age: a } = person;

// Array destructuring
const [first, second] = [1, 2, 3];

// Default values
const { city = "Unknown" } = { name: "Alice" };

// Rest elements
const [head, ...rest] = [1, 2, 3, 4, 5];

Spread operator

// Array spread
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5];

// Object spread
const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 };

Nullish coalescing

const input = null;
const value = input ?? "default"; // "default"

// Optional chaining
const user = { address: { city: "NYC" } };
const city = user?.address?.city; // "NYC"

Mini Practice

Write TypeScript code that:

  1. Uses let and const with type annotations
  2. Creates a function with optional and default parameters
  3. Destructures an object and an array
  4. Uses template literals and nullish coalescing

Up Next

In the next lesson, you'll learn about Types — TypeScript's type system.

Related Topics

Frequently Asked Questions about Syntax

What is Syntax in TypeScript?

Syntax is a fundamental concept in TypeScript. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Syntax?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Syntax.

Why is Syntax important in TypeScript?

Syntax is essential for TypeScript development. Understanding this concept will help you write better code and solve real-world problems more effectively.