Getting Started with TypeScript: A Comprehensive Guide

TypeScript is a superset of JavaScript that introduces static types, improving code quality and development experience. In this article, we'll cover the basics of TypeScript, its benefits, and provide code snippets to help you start using it in your projects.

Why Use TypeScript?

TypeScript provides several advantages over plain JavaScript:

  • Static Typing: Helps catch errors during development.
  • Improved IDE Support: Enhanced autocompletion and refactoring tools.
  • Better Documentation: Self-documenting code with type annotations.
  • Easier Maintenance: Type checks make large codebases more manageable.

Installation

To install TypeScript, use npm or yarn:

npm install -g typescript

You can also initialize TypeScript in your project:

npx tsc --init

Basic Types

TypeScript provides several built-in types that help you write more robust code. Here are some examples:

let isDone: boolean = false
let age: number = 30
let userName: string = 'Karim'

Type Inference

Interfaces define the shape of objects, making it easier to ensure consistency.

interface User {
  name: string
  age: number
}

const user: User = {
  name: 'Karim',
  age: 30,
}

Functions

TypeScript allows you to define the types of function parameters and return values.

function greet(name: string): string {
  return `Hello, ${name}!`
}

console.log(greet('Karim'))

Classes

Classes in TypeScript are similar to classes in JavaScript, but with added type safety.

class User {
  name: string
  age: number

  constructor(name: string, age: number) {
    this.name = name
    this.age = age
  }

  greet() {
    console.log(
      `Hello, my name is ${this.name} and I am ${this.age} years old.`,
    )
  }
}

let user = new User('Karim', 30)
user.greet()

Enums

Enums in TypeScript are a way to define a set of named constants.

enum Color {
  Red,
  Green,
  Blue,
}

let color: Color = Color.Red

Type Aliases

Type aliases allow you to create custom names for existing types.

type Point = {
  x: number
  y: number
}

type Size = {
  width: number
  height: number
}

function createPoint(x: number, y: number): Point {
  return { x, y }
}

function createSize(width: number, height: number): Size {
  return { width, height }
}

let point: Point = createPoint(10, 20)
let size: Size = createSize(100, 200)

Type Guards

Type guards allow you to narrow down the type of a variable based on a condition.

function isNumber(value: any): value is number {
  return typeof value === 'number'
}

function isString(value: any): value is string {
  return typeof value === 'string'
}

function isObject(value: any): value is object {
  return typeof value === 'object'
}

let number: number = 10
let string: string = 'Hello, world!'
let object: object = { name: 'Karim' }

if (isNumber(number)) {
  console.log(number)
}

Generics

Generics enable you to create reusable components that work with various types.

function identity<T>(arg: T): T {
  return arg
}

console.log(identity<number>(42))
console.log(identity<string>('Hello'))

Conclusion

TypeScript enhances JavaScript by adding static types, making your code more predictable and easier to debug. With features like interfaces, classes, and generics, TypeScript is a powerful tool for modern web development. Start using TypeScript in your projects to improve your code quality and development workflow.