Interview Questions

TypeScript Syntax Crash Course: A Guide for Junior JS Developers

Author: Interview Questions Posted 3 days ago 61 min read

TypeScript Syntax Part 1: The Basics

If you know JavaScript, you already know 80% of TypeScript. TypeScript is simply JavaScript with static typing added on top.

In this course, we will cover the foundational syntax you need to start writing TypeScript today. Let’s dive in!


1. The Basics: Primitive Types

In JavaScript, you declare variables with let or const. In TypeScript, you do the same, but you can add a type annotation using a colon (:).

// JavaScript
let firstName = "Alice";
let age = 25;
let isDeveloper = true;

// TypeScript
let firstName: string = "Alice";
let age: number = 25;
let isDeveloper: boolean = true;

If you try to assign the wrong type of data to these variables later, TypeScript will yell at you (which is exactly what we want!):

age = "twenty-five"; // Error: Type 'string' is not assignable to type 'number'.

2. The Magic of Type Inference

You don't always have to write out the types. TypeScript has a smart compiler that uses Type Inference. If you assign a value immediately, TypeScript guesses the type for you.

// You don't need to write `: string` here. 
// TS knows it's a string because of "Bob".
let lastName = "Bob"; 

// Error: Type 'number' is not assignable to type 'string'.
lastName = 42; 

Pro Tip: Only use explicit type annotations when you declare a variable without assigning it immediately, or when TypeScript can't guess what you mean.

3. Arrays

Typing arrays is very common. You simply take the type of the items inside the array and add [] to the end.

let scores: number[] = [90, 85, 100];
let names: string[] = ["Alice", "Bob", "Charlie"];

// Alternative syntax (Generics):
let isActive: Array<boolean> = [true, false, true];

// TS prevents you from putting a string in a number array:
scores.push("eighty"); // Error!

4. Functions: Parameters and Return Types

Functions are where TypeScript really shines. You can type both the arguments (parameters) going into the function and the value returning from it.

// parameter: type, parameter: type -> : return type
function addNumbers(a: number, b: number): number {
  return a + b;
}

// Arrow function syntax
const multiply = (x: number, y: number): number => {
  return x * y;
};

// Functions that don't return anything use the 'void' type
function logMessage(message: string): void {
  console.log(message);
}

// --- How to use them ---

// 1. Calling them directly
let sum = add(5, 10);        // sum is now 15
let product = multiply(4, 5); // product is now 20

console.log(sum);     // Output: 15
console.log(product); // Output: 20

// 2. Passing them as callbacks to other functions
// Because 'add' matches the MathOperation shape, we can pass it around safely.
function calculateAndPrint(operation: MathOperation, num1: number, num2: number) {
    const result = operation(num1, num2);
    console.log(`The result is: ${result}`);
}

calculateAndPrint(add, 10, 20);      // Output: The result is: 30
calculateAndPrint(multiply, 10, 20); // Output: The result is: 200

5. Objects: Interfaces and Types

In JavaScript, objects hold your application's state. In TypeScript, we define the "shape" of these objects using interface or type.

Using interface (Recommended for Objects)

interface User {
  name: string;
  age: number;
  isAdmin: boolean;
}

// Now we can use 'User' as a type!
const myUser: User = {
  name: "Alice",
  age: 28,
  isAdmin: false
};

Optional Properties (?)

Sometimes an object might have a property, but it doesn't have to. Use a question mark ? to make it optional.

interface Product {
  id: number;
  title: string;
  description?: string; // Optional!
}

const laptop: Product = { id: 1, title: "MacBook" }; // Works perfectly without description

6. Union Types (This OR That)

Sometimes a variable or function parameter can legitimately be more than one type. You can use the pipe | symbol to create a Union Type.

// The ID can be a string OR a number
let userId: string | number;

userId = 101;      // Valid
userId = "A-101";  // Valid
userId = true;     // Error: Type 'boolean' is not assignable.

// Great for specific string values (String Literal Types)
let status: "loading" | "success" | "error";
status = "success"; // Valid
status = "failed";  // Error!

7. The Escape Hatch: any

Sometimes you don't know the type of a value (e.g., data from a messy third-party API), or you are slowly migrating a JS file to TS. You can use the any type.

let mysteryBox: any = "Hello";
mysteryBox = 42; 
mysteryBox = { name: "Bob" };

Warning: Using any completely disables TypeScript's checking for that variable. Use it as a last resort! If you use any everywhere, you are just writing JavaScript with extra steps.

8. Generics (A Quick Intro)

Think of Generics as "variables for types." They allow you to write a function or interface that works with different types without losing type safety. They are usually represented by a <T>.

// <T> captures whatever type the user passes in
function getFirstItem<T>(array: T[]): T {
  return array[0];
}

const numbers = [1, 2, 3];
// TS knows this returns a number
const firstNumber = getFirstItem(numbers); 

const strings = ["a", "b", "c"];
// TS knows this returns a string
const firstString = getFirstItem(strings); 

What's Next?

Congratulations! You now know the core syntax of TypeScript.

The best way to learn is by doing. Next time you write a JavaScript function, try putting it in a .ts file and adding types to the parameters. Let your code editor guide you—the red squiggly lines are your friends!


TypeScript Syntax Part 2: Interfaces, Types, and Classes Explained

In our first crash course, we covered the basics of TypeScript: primitive types, arrays, and basic functions. But to build real-world applications, you need to model complex data structures and object-oriented patterns.

In this second part, we will dive into what interfaces actually mean, how to type functions inside objects, how to use the type keyword, and how TypeScript supercharges JavaScript classes.


1. What Exactly is an Interface?

If you come from a pure JavaScript background, the concept of an interface might feel completely foreign.

Think of an interface as a strict legal contract or a blueprint for an object. It does not hold any actual data, and it doesn't even exist when your code is compiled into JavaScript. Its only job is to tell TypeScript: "Any object that claims to be of this type MUST have exactly these properties and methods."

// The Blueprint (Contract)
interface Car {
  brand: string;
  year: number;
}

// The Actual Object
const myCar: Car = {
  brand: "Toyota",
  year: 2022
  // If we misspell 'brand' or forget 'year', TypeScript will throw an error!
};

2. Functions Inside Interfaces

Objects don't just hold data; they hold behaviors (functions). You can describe functions inside an interface in two ways.

A. Methods attached to an object

If your object has a method, you can define its parameters and return type right inside the interface:

interface User {
  name: string;
  // This means: "The object must have a 'greet' function that takes no arguments and returns a string"
  greet(): string; 

  // Alternatively, you can use arrow function syntax:
  // greet: () => string;
}

const alice: User = {
  name: "Alice",
  greet() {
    return `Hello, my name is ${this.name}`;
  }
};

B. Standalone Function Signatures

You can also use an interface to describe a standalone function itself, rather than an object with properties.

interface MathOperation {
  // Takes two numbers, returns a number
  (x: number, y: number): number; 
}

const add: MathOperation = (a, b) => a + b;
const multiply: MathOperation = (a, b) => a * b;

3. The type Keyword (Type Aliases)

You might have seen the type keyword and wondered how it differs from interface.

A type alias is exactly what it sounds like: a nickname for a type. While interface is strictly used for defining the shape of objects, type can be used for objects, primitives, unions, and more.

When to use type:

1. For Union Types (Combining types)
You cannot do this with an interface.

type UserID = string | number;

let id1: UserID = 123;
let id2: UserID = "ABC-123";

2. For creating specific custom types

type Status = "pending" | "approved" | "rejected";

function updateStatus(newStatus: Status) {
  // TypeScript will only allow those three specific strings
}

3. For Object Shapes (Just like interfaces)

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

Rule of thumb for beginners: Use interface when defining the shape of an object or a class. Use type when you need a union (|) or are giving a nickname to a simpler value.

More usage of type: Utility Types and Intersection Types

4. Classes in TypeScript

JavaScript introduced the class keyword in ES6. TypeScript takes JavaScript classes and adds strict typing and access modifiers (public, private, protected).

In regular JavaScript, you can just start assigning this.name = name in the constructor. In TypeScript, you must declare your class properties upfront.

class Animal {
  // 1. You MUST declare the fields and their types here first
  // These are instance properties (Unique to every animal)
  name: string;
  age: number;

  // Static property (Belongs to the Animal class itself, shared)
  static totalAnimalsCreated: number = 0; 

  // 2. Then you assign them in the constructor
  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
    Animal.totalAnimalsCreated++; // Increment the shared static property
  }

  // 3. Methods are typed just like regular functions
  speak(): void {
    console.log(`${this.name} makes a noise.`);
  }
}

const dog = new Animal("Buddy", 3); // Instance
console.log(dog.name); // "Buddy"
dog.speak();

Combining Classes and Interfaces (implements)

One of the most powerful features of TypeScript is forcing a class to follow an interface contract using the implements keyword. This guarantees your class has the required methods and properties.

// The Contract
interface Player {
  username: string;
  play(): void;
}

// The Class that signs the contract
class VideoGamePlayer implements Player {
  username: string;

  constructor(username: string) {
    this.username = username;
  }

  play(): void {
    console.log(`${this.username} is now playing the game!`);
  }
}

// If VideoGamePlayer forgot to include the `play()` method, 
// TypeScript would immediately throw a compile error.

Summary

  • interface: A strict blueprint that defines the shape of an object.
  • Functions in Interfaces: You can easily define what arguments a method takes and what it returns right inside the blueprint.
  • type: A versatile way to create nicknames for types, especially useful for unions (string | number).
  • Classes: TypeScript requires you to declare class fields upfront and allows you to enforce class structures using implements interface.

By mastering these structures, you transition from simply adding types to variables, to actually architecting robust, scalable applications!