TypeScript Crash Course

TypeScript Crash Course

Hello Everyone! Welcome to My TypeScript classroom where you are going to learn the basics of typescript language. So let's jump right into it.

What is typescript?

Is it a completely new programming language or what?

The answer is NO. It's not a new language. Most of the people reading this may used javascript before. TypeScript is built on top of the JavaScript language. TypeScript is a superset of the javascript language. If it’s built on top of the javascript language, what makes it different or the real need for this typescript?

I will give some cons of javascript that typescript is solving.

  • Javascript is a dynamically typed language, which means that the variable types are determined at the runtime. This can lead to type-related errors which can only be caught at the runtime.
const a = 34;
const b = 'hello world'
const c = true
  • TypeScript is a statically typed language, which means that developers can define the type of the variable, function parameters and return values. These annotations can be checked at the compile time, thus reducing the runtime errors.
let message: string = 'Hello, World!';
//message - variable name
//string - type
  • Javascript has limited tooling for code analysis and refactoring. So it may be hard to maintain large codebases.

  • Typescript provides better tooling support. This improves code quality, readability, and maintainability, especially in larger projects.

  • JavaScript has limited error checking before runtime, leading to runtime errors that can be difficult to debug.

  • TypeScript performs extensive error checking at compile-time. This helps catch errors early in the development process, reducing the likelihood of runtime errors and making debugging easier.

  • Scaling JavaScript projects can be challenging due to the absence of solid typing and modularity, which can lead to codebase complexity and maintenance issues.

  • TypeScript's strong typing and support for interfaces and classes make it easier to scale projects. Developers can define clear interfaces and encapsulate code in classes, promoting modularity and maintainability.

Types in Typescript.

Primitive Types:

  • Number
  • String

  • Boolean

  • Undefined/Null

  • BigInt

  • Void, etc.

These are some of the major Primitive types in the typescript.

Number: Numbers are more than digits, they are precise, in numbers we can have integer values or float values.

let age: number = 25;
let pi: number = 3.14159;

String: Strings are letters, words, sentences or even emojis. Typescript ensures strings are treated as texts, so it's easier for string manipulations.

let greeting: string = "Hello, TypeScript!";
let emoji: string = "🚀";

Boolean: Boolean is true or false values for logical operations.

let isStudent: boolean = true;
let hasAccess: boolean = false;

Undefined/Null: In some cases the values for some variables don't exist. So they are represented by either Null/Undefined

let undefinedValue: undefined = undefined;
let nullValue: null = null;

BigInt: BigInt are Integers, but larger for arbitrary precision. Large numbers can’t be handled by the ‘number’ type

const bigValue: bigint = 1234567890123456789012345678901234567890n;

Void: Void represents the absence of value. Often used as the return type of function if the function is not returning any type of value.

function logMessage(message: string): void {
  console.log(message);
}

there are some more types of typescripts. You can do a simple Google search to read more on that.

Type Inference and Type Assignment -

Typescript assumes the type of the variable that is initialized based on its value. So we don’t have to worry even if we didn’t explicitly assign types using annotations.

let username = "Alice"; // TypeScript infers 'string' type
let age: number = 30;   // Explicit type assignment

Structural Types

Structural types are a fundamental concept in the typescript which makes your code more flexible and adaptable. Here's a closer look at structural types in TypeScript:

Object Types: In typescript, if two objects have the same structure, typescript considers them as compatible. even if they were created differently.

const person1 = { name: "John", age: 52 };
const person2 = { name: "Bob", age: 25 };

Function Types: Typescript checks the type of parameters and return type of the functions match.

function logMessage(message: string): void {
  console.log(message);
}

Array Types: Arrays are checked based on the structure of their elements. In this case, both arr is an array of numbers, and TypeScript ensures that only numbers are added to it.

const arr: number[] = [1, 2, 3];

Tuple Types: Tuples are like arrays with a fixed number of elements whose types are known.

let student: [number, string] = [10, "John"];
//10: rollNumber, John: Name

Enum Types: Enums are a way of giving a more friendly name to a set of numeric values.

enum Direction {
  Up,
  Down,
  Left,
  Right,
}

let move: Direction = Direction.Up; // move is now a meaningful symbol

Any Type: Any is used when you don’t need the typescripts type checking for that variable if you need more flexibility for that variable.

let dynamicValue: any = "I can be anything!";
dynamicValue = 42; // TypeScript won't complain

Literal Types: Literal types allow you to specify exact values as types. This can make your code more precise and help catch bugs early.

type Gender = "male" | "female";
let userGender: Gender = "female"; // Only "male" or "female" allowed

Structural typing in TypeScript keeps your code agile, allowing you to focus on the shape of things, not their names. It's a powerful tool for creating flexible and robust applications!

Advanced TypeScript;

Let's continue our TypeScript exploration by delving into some powerful language features: Interfaces, Modules, and Classes. These building blocks enable you to write organized, maintainable, and scalable code.

1/ Interfaces: Interfaces define the structure of objects, specifying which properties and methods an object should have. They're like blueprints for creating objects with specific shapes.

interface Person {
  name: string;
  age: number;
}

const alice: Person = { name: "Alice", age: 30 };

Interfaces are incredibly useful for ensuring consistent data structures and contracts in your code.

2/ Modules: Modules help you organize your code into reusable and maintainable pieces. You can split your code into different files, each containing its own module, and then import and use those modules in other parts of your application.

// Math.ts
export function add(a: number, b: number): number {
  return a + b;
}

// App.ts
import { add } from "./Math";
console.log(add(5, 3)); // Outputs: 8

Modules promote code encapsulation, reusability, and maintainability.

3/ Classes: Classes in TypeScript allow you to define blueprints for objects with properties and methods. They encapsulate data and behaviour into a single unit, providing a clean and organized way to structure your code.

class Dog {
  constructor(public name: string) {}
  bark() {
    console.log(`${this.name} says woof!`);
  }
}

const myDog = new Dog("Buddy");
myDog.bark(); // Outputs: Buddy says woof!

Classes are crucial for building complex objects and for adhering to object-oriented programming principles.

4/ Inheritance and Interfaces: You can use inheritance to create new classes based on existing ones, and you can implement interfaces to ensure a class adheres to a specific contract.


class Animal {
  constructor(public name: string) {}
  makeSound() {
    console.log(`${this.name} makes a sound.`);
  }
}

class Cat extends Animal {
  makeSound() {
    console.log(`${this.name} meows.`);
  }
}

const fluffy = new Cat("Fluffy");
fluffy.makeSound(); // Outputs: Fluffy meows.

The End.

So, whether you're a JavaScript developer looking to level up your skills or a newcomer eager to explore the world of web development, TypeScript is a valuable addition to your toolkit. Stay curious, keep coding, and let TypeScript empower your web development projects.

Thank you.

Share your thoughts on this on your socials and tag me @my X(twitter) handle.

follow me on