TypeScript

TypeScript

A Beginner's Guide to TypeScript

TypeScript is a powerful, statically typed superset of JavaScript that brings optional static types, classes, and interfaces to the language. It provides a way to catch errors early in the development process and make the code more robust and maintainable. This guide will help you get started with TypeScript, covering the basics and some advanced concepts.

What is TypeScript?

TypeScript is developed and maintained by Microsoft. It builds on JavaScript by adding static type definitions, which can help you catch errors during development rather than at runtime. TypeScript code is transpiled to plain JavaScript, making it compatible with any environment that runs JavaScript.

Setting Up TypeScript

To get started with TypeScript, you'll need to install it via npm:

npm install -g typescript        

You can compile TypeScript files using the TypeScript compiler (tsc). For example, to compile a file named app.ts, you would run:

tsc app.ts        

Basic Types

TypeScript provides several basic types to enforce type safety:

let isDone: boolean = false;
let age: number = 25;
let name: string = "John";
let list: number[] = [1, 2, 3];
let tuple: [string, number] = ["hello", 10];        

Classes and Interfaces

Classes in TypeScript are similar to ES6 classes but with additional type annotations. Interfaces allow you to define the structure of an object.

Classes

class Person {
  name: string;
  age: number;

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

  greet() {
    console.log(`Hello, my name is ${this.name}.`);
  }
}

let john = new Person("John", 30);
john.greet();        

Interfaces

interface Person {
  name: string;
  age: number;
  greet(): void;
}

let john: Person = {
  name: "John",
  age: 30,
  greet() {
    console.log("Hello, my name is " + this.name);
  },
};

john.greet();        

Advanced Types

TypeScript offers advanced types to create complex type definitions.

Union Types

let value: string | number;
value = "hello";
value = 42;        

Type Aliases

type StringOrNumber = string | number;
let value: StringOrNumber;
value = "hello";
value = 42;        

Generics

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

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

let output1 = identity<string>("myString");
let output2 = identity<number>(100);        

Decorators

Decorators are a special kind of declaration that can be attached to a class, method, accessor, property, or parameter.

function readonly(target: any, key: string) {
  Object.defineProperty(target, key, {
    writable: false,
  });
}

class Person {
  @readonly
  name: string = "John";
}

let person = new Person();
person.name = "Doe"; // Error: Cannot assign to 'name' because it is a read-only property.        

Modules and Namespaces

Modules in TypeScript are files that contain import and export statements. Namespaces are a way to organize code in a global scope.

Modules

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

// main.ts
import { add } from "./math";
console.log(add(2, 3));        

Namespaces

namespace MathUtils {
  export function add(a: number, b: number): number {
    return a + b;
  }
}

console.log(MathUtils.add(2, 3));        

Webpack

Webpack is a popular module bundler for JavaScript applications. To use TypeScript with Webpack, you need to install the necessary loaders and plugins:

npm install --save-dev typescript ts-loader webpack webpack-cli        

Then, create a webpack.config.js file:

const path = require("path");

module.exports = {
  entry: "./src/index.ts",
  module: {
    rules: [
      {
        test: /\.ts$/,
        use: "ts-loader",
        exclude: /node_modules/,
      },
    ],
  },
  resolve: {
    extensions: [".ts", ".js"],
  },
  output: {
    filename: "bundle.js",
    path: path.resolve(__dirname, "dist"),
  },
};        

Using Third-Party Libraries with TypeScript

Many popular JavaScript libraries have TypeScript type definitions available, which you can install from the DefinitelyTyped repository.

For example, to use lodash with TypeScript, you can install its type definitions:

npm install lodash @types/lodash        

Then, you can use it in your TypeScript code:

import * as _ from "lodash";

let numbers = [1, 2, 3, 4, 5];
console.log(_.shuffle(numbers));        

Conclusion

TypeScript is a powerful tool that adds static typing to JavaScript, making your code more predictable and easier to debug. By learning TypeScript, you'll be able to catch errors early, improve code quality, and enhance your development experience. Whether you're building small projects or large applications, TypeScript is a valuable addition to your toolkit.

Happy coding!

Sounds intriguing. TypeScript seems like a game-changer. I can't wait to dive into your article Om Jamnekar

To view or add a comment, sign in

More articles by Om Jamnekar

  • TypeScript Goes Go: Microsoft’s Bold Move to Boost Performance

    Microsoft has just shaken up the developer world by announcing that TypeScript, which was originally written in…

    6 Comments
  • Macros in Dart to Simplify Boilerplate Code

    In Dart, macros provide a powerful way to automate the generation of boilerplate code, enhancing productivity and…

  • NodeJS

    In the dynamic world of application development, Node.js has emerged as a transformative technology.

  • Impeller

    🚀 Flutter Devs, Meet Impeller: The New Engine That'll Turbocharge Your Apps! 🚀 Hey Flutter enthusiasts! If you’re…

  • Flutter 3.19

    🌟 Exciting Updates in Flutter 3.19! 🌟 Flutter continues to evolve, bringing new features and improvements with each…

  • getXBuilder(Flutter)

    Flutter with GetXBuilder: A Comprehensive Guide Introduction: Flutter, known for its fast development and expressive…

  • ML with Flutter

    Machine Learning with ML Kit by Firebase and Flutter Introduction to ML Kit by Firebase ML Kit by Firebase stands as a…

  • Shared Preferences

    In the dynamic world of mobile app development, where user preferences play a pivotal role, the ability to seamlessly…

  • Go

    Empowering Your IT Career with Go (Golang): A Comprehensive Guide: In the ever-evolving world of software development…

  • Rhai Scripting and Rust

    Rust is a systems programming language known for its focus on safety, performance, and concurrency. Rhai, on the other…

Insights from the community

Others also viewed

Explore topics