← Back to Blog

typescript-for-beginners

Fapskom IT

Published

3 min read

TypeScript for Beginners: Type Safety Made Simple

JavaScript is incredibly flexible, but that flexibility often comes at a cost: runtime bugs, broken refactoring, and silent errors that creep into production. TypeScript solves this by adding static types to JavaScript, giving you compile-time safety and a massive boost to your developer productivity.

In this guide, we'll cover the essential TypeScript features you need to start building with confidence.


1. What is TypeScript?

TypeScript is a strongly typed superset of JavaScript. This means two important things:

  1. Any valid JavaScript is also valid TypeScript. You don't need to rewrite your code from scratch to adopt TypeScript.
  2. TypeScript compiles down to plain JavaScript. Browsers and Node.js don't execute TypeScript directly. The compiler (tsc) checks your code and outputs clean, compatible JavaScript.

2. Basic Types

TypeScript infers types where possible, but you can also annotate them explicitly using a colon (:):

// Explicit annotations
let isCompleted: boolean = false;
let age: number = 26;
let firstName: string = "Faiz";

// Type inference (TypeScript knows these types automatically!)
let isDone = true; // boolean
let count = 42;    // number
let username = "fapskom"; // string

Arrays and Tuples

You can specify array types by appending [] to the type, or by using Array<type>:

let scores: number[] = [90, 85, 100];
let tags: Array<string> = ["React", "TypeScript"];

// Tuples have a fixed number of elements with predefined types
let userSession: [string, number] = ["faiz_adi", 1716382900];

3. Interfaces and Type Aliases

To define complex object shapes, you can use interface or type. Interfaces are highly extensible and ideal for defining API responses or component props.

interface User {
  id: string;
  name: string;
  email: string;
  isAdmin?: boolean; // Optional property (notice the '?')
}

const activeUser: User = {
  id: "usr_9921",
  name: "Faiz Adi",
  email: "faiz@fapskom.com",
};

Type Aliases

Type aliases can represent primitives, unions, and complex types:

type ID = string | number; // Union type (can be string OR number)
type ThemeMode = "light" | "dark" | "system";

let currentTheme: ThemeMode = "dark";
// let invalidTheme: ThemeMode = "blue"; // ❌ Error: Type '"blue"' is not assignable to type 'ThemeMode'.

4. Functions with Type Safety

TypeScript allows you to specify types for arguments and the return value of functions:

function calculateTotal(price: number, tax: number = 0.1): number {
  return price + price * tax;
}

// Arrow function syntax
const logMessage = (msg: string): void => {
  console.log(`[LOG]: ${msg}`);
};

If a function doesn't return a value, annotate the return type as void.


5. Understanding Generics

Generics are like variables for types. They allow you to write reusable, flexible helper functions that maintain strict type relationships between arguments and return values.

Suppose you want a function that returns the first element of an array:

// Without Generics: we lose type information (returns 'any')
function getFirstItem(arr: any[]): any {
  return arr[0];
}

// With Generics (represented by <T>)
function getFirst<T>(arr: T[]): T {
  return arr[0];
}

const numbers = [1, 2, 3];
const firstNumber = getFirst(numbers); // Automatically typed as 'number'

const names = ["Faiz", "Adi"];
const firstNameVal = getFirst(names); // Automatically typed as 'string'

6. Configuring TypeScript (tsconfig.json)

Every TypeScript project is configured using a tsconfig.json file in the root. Here are the core settings you should care about:

{
  "compilerOptions": {
    "target": "es2022",               // Output modern JavaScript
    "module": "commonjs",             // How modules are resolved
    "strict": true,                   // Enable strict type-checking (Highly Recommended!)
    "esModuleInterop": true,          // Better compatibility with ES modules
    "skipLibCheck": true,             // Skip checking type declaration files (.d.ts)
    "forceConsistentCasingInFileNames": true
  }
}

Why TypeScript is a Game Changer

Adopting TypeScript pays massive dividends:

  1. Self-Documenting Code: Your editors show exact object shapes and function signatures as you type.
  2. Safe Refactoring: Rename an interface field, and the TypeScript compiler will immediately highlight every single place in your app that needs to be updated.
  3. No More Undefined Errors: The strict null compiler flag prevents the infamous Cannot read property 'x' of undefined from crashing your production app.

TypeScript is standard in the modern web ecosystem. Once you start writing type-safe code, you will never want to go back to vanilla JavaScript! 🚀