The Talent500 Blog
Getting Started with TypeScript 1

Getting Started with TypeScript

Ever since TypeScript came into existence, JavaScript developers can now leverage the power of TypeScript. TypeScript is a syntactical superset of JavaScript, and it can improve development efficiency.

In simpler terms, TypeScript allows us to add types to our code. This means that we can specify the expected data types for function parameters and return values. With TypeScript, we can have more clarity and predictability regarding the values that are passed into functions and the values that functions will return.

The TypeScript compiler compiles the TypeScript code and returns a JavaScript Code. And all the syntax of JavaScript is readily available in TypeScript.

Getting Started with TypeScript 2

In this comprehensive blog, we will delve into TypeScript. By the end of this article, you will have a solid understanding of TypeScript, enabling you to use it on your dream project with confidence, utilizing TypeScript’s capabilities.

So, Let’s get started

Installing TypeScript

To start using TypeScript, you first need to install it on your machine. Assuming you have Node.js installed on your computer, run the following command to install TypeScript:

npm install -g typescript

This command will install TypeScript globally on your system, making it accessible from any directory. Now you can proceed to create TypeScript files, write code, and compile them into JavaScript using the TypeScript compiler (tsc).

To execute TypeScript, you can use the npx tsc command followed by the filename you want to compile. If you want to automatically recompile your TypeScript files whenever there occurs a change, you can use the –watch flag. This will set TypeScript to monitor your files for modifications and recompile them automatically.

Let’s now compile this TypeScript and see what happens:

let count: number = 10;

let pi: number = 3.14;

let message: string = “Hello, TypeScript!”;

let name: string = “John Doe”;

let person: object = { name: “John”, age: 25 };

let myArray: object[] = [{}, {}, {}];

let numbers: number[] = [1, 2, 3, 4];

let names: string[] = [“Alice”, “Bob”, “Charlie”];

Getting Started with TypeScript 3

You can see that at the end, everything is compiled into raw JavaScript. What TypeScript offers is the ability to have much more maintainable code compared to writing JavaScript.

Type Annotation in TypeScript

Type annotations in TypeScript allow you to explicitly specify the types of variables, function parameters, and function return values. By providing type annotations, you can add static typing to your code and catch potential type-related errors during development.

let age: number = 25; // Type annotation for a variable

function greet(name: string): void { // Type annotation for a function parameter and return type

  console.log(“Hello, “ + name);

}

let numbers: number[] = [1, 2, 3]; // Type annotation for an array of numbers

let person: { // Type annotation for an object with specific properties

  name: string;

  age: number;

} = {

  name: “John”,

  age: 30,

};

Why TypeScript Instead of Plain JavaScript?

We know that JavaScript is a powerful and widely used programming language, there are several reasons why developers choose to use TypeScript over plain JavaScript for certain projects. Don’t get confused, TypeScript is like a superset of JavaScript.

Getting Started with TypeScript 4

 Here are some key advantages of TypeScript:

  • Static Typing: TypeScript adds static typing to JavaScript, enabling early detection of type errors and providing better tooling support.
  • Early Detection of Errors: With static typing, TypeScript catches many common errors at compile-time rather than during runtime. This provides instant feedback on type mismatches, missing properties, and other issues, allowing developers to fix errors earlier in the development process.
  • Improved Code Maintainability: TypeScript’s static typing makes code easier to read and maintain. By clearly defining types, the code acts like self-documentation, making it simple for developers to understand and work on projects together. Also, IDEs and tools offer improved code navigation and refactoring support for TypeScript code.
  • Type Inference: TypeScript’s type inference mechanism infers types based on assignment and usage, reducing the need for explicit type annotations.
  • Advanced Type System: TypeScript offers advanced types like unions, intersections, literal types, and type aliases, allowing for precise type annotations and powerful abstractions.
  • Optional Static Typing: TypeScript allows the gradual adoption of static typing by supporting any type, which can be used when the type is unknown or when working with existing JavaScript code.
  • ECMAScript Compatibility: TypeScript is a superset of JavaScript, meaning all valid JavaScript code is also valid TypeScript code. It supports the latest ECMAScript features and provides better tooling for transpiring to different JavaScript versions.
  • Code Navigation and IntelliSense: TypeScript enables enhanced code navigation, autocompletion, and error checking in modern IDEs, improving developer productivity.
  • ES Modules and CommonJS Support: TypeScript supports both ES Modules and CommonJS module systems, making it easy to work with different module formats.
  • Readability and Maintainability: TypeScript’s static typing enhances code readability, provides self-documenting code, and improves maintainability by catching potential issues at compile time.

Types in JavaScript

TypeScript allows static typing, enabling developers to specify the types of variables, function parameters, and return values. This makes the code more reliable, as we can easily understand what a function expects and what it will return. 

Here are the commonly used types in TypeScript:

Undefined

Represents an undefined value. It is a subtype of all other types.

let undefinedValue: undefined = undefined;

Null

Represents a null value. Like undefined, it is a subtype of all other types.

let nullValue: null = null;

Boolean

Represents logical values, either true or false.

let isDone: boolean = false;

let hasStarted: boolean = true;

Number

Represents numeric values, including integers, floating-point numbers, and special numeric values like Infinity and NaN.

let count: number = 10;

let pi: number = 3.14;

String

Represents textual data, such as a sequence of characters. It can also include numbers, but inside double quotes or single quotes.

let message: string = “Hello, TypeScript!”;

let Company: string = “Talent500”;

Object

Represents a general non-primitive value, including arrays, functions, and objects.

let person: object = { name: “John”, age: 25 };

let myArray: object[] = [{}, {}, {}];

Array 

Represents an array of values of a specific type. For example, number[] represents an array of numbers.

let numbers: number[] = [1, 2, 3, 4];

let names: string[] = [“Alice”, “Bob”, “Charlie”];

Tuple

Represents an array with a fixed number of elements, where each element can have its type. For example, [string, number] represents a tuple with a string followed by a number.

let tuple: [string, number] = [“Alice”, 25];

Enum

Represents a set of named constant values. Enums provide a way to define a set of related values with friendly names.

enum Color {

  Red,

  Green,

  Blue

}

let selectedColor: Color = Color.Red;

Any

Represents a value of any type. It allows dynamic typing and is often used when the type is unknown or when working with existing JavaScript code.

let dynamicValue: any = 10;

dynamicValue = “Hello”;

Void

Represents the absence of any type. It is commonly used as the return type for functions that do not return a value.

function logMessage(): void {

  console.log(“This is a log message.”);

}

Advanced Types in TypeScript

In addition to the basic types, TypeScript also offers several advanced types that enhance the expressiveness and precision of type annotations.

 These advanced types enable developers to create powerful abstractions and ensure more accurate type-checking. Here are some most used advanced types in TypeScript:

Unions

TypeScript allows combining multiple types using the union operator (Pipe) |. This creates a union type that can hold the values of any of the constituent types.

let myVariable: number | string;

myVariable = 10;      // Valid

myVariable = “Hello”; // Valid

myVariable = true;    // Invalid

Intersections

TypeScript supports creating intersection types using the intersection operator &. This combines multiple types into a single type that must satisfy all the constituent types. 

interface A {

    propA: number;

  }

  interface B {

    propB: string;

  }

  let myVariable: A & B;

  myVariable = { propA: 10, propB: “Hello” }; // Valid

  myVariable = { propA: 10 };                 // Invalid

  myVariable = { propB: “Hello” };            // Invalid

 Literal Types

TypeScript allows defining literal types that narrow down the possible values of a variable to a specific literal value. This is done using string, number, boolean, or enum literals. For example:

let status: “success” | “error”;

status = “success”; // Valid

status = “error”;   // Valid

status = “failed”// Invalid

Type Aliases

TypeScript provides type aliases that allow developers to create custom names for complex types. This improves code readability and reduces duplication. For example:

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

let p: Point = { x: 10, y: 20 };

Type Guards

TypeScript supports type guards, which are conditional statements or functions that narrow down the type of a variable based on a specific condition. This enables more precise type checking and allows for safer code. For example:

function isString(value: unknown): value is string {

    return typeof value === “string”;

  }

  function processValue(value: unknown) {

    if (isString(value)) {

      // Inside this block, TypeScript knows that ‘value’ is of type ‘string’

      console.log(value.toUpperCase());

    } else {

      console.log(“Value is not a string.”);

    }

  }

 

These advanced types in TypeScript provide developers with powerful tools to express complex types and enforce stronger type checking.

TypeScript Generics

Generics in TypeScript provide a way to write reusable and type-safe code by introducing placeholders for types that can be specified when using the generic entities. Generics allow functions, classes, and interfaces to operate on a variety of types rather than being restricted to a specific type.

class Repository<T> {

    private items: T[];

    constructor() {

      this.items = [];

    }

    addItem(item: T): void {

      this.items.push(item);

    }

    getAllItems(): T[] {

      return this.items;

    }

 

   getItemById(id: number): T | undefined {

      return this.items.find(item => item.id === id);

    }

  }

 

  // Usage examples

  interface User {

    id: number;

    name: string;

  }

 

  const userRepo = new Repository<User>();

  userRepo.addItem({ id: 1, name: “John” });

  userRepo.addItem({ id: 2, name: “Alice” });

 

  const allUsers = userRepo.getAllItems();

  console.log(allUsers); // Output: [{ id: 1, name: “John” }, { id: 2, name: “Alice” }]

 

  const userById = userRepo.getItemById(1);

  console.log(userById); // Output: { id: 1, name: “John” }

 In this example, the Repository class is defined as a generic class with the type parameter T. It shows how the Repository class can be used with a specific type, in this case, the User interface.

Most of the modern-day frameworks have excellent support for TypeScript, and lately, it has become the industry standard to use TypeScript. Learning TypeScript can be a win-win situation for you if you already know JavaScript.

Wrapping it up

In this blog, we have looked into TypeScript and its importance in the modern day. We have also discussed some of its key features and examined several examples of using different types. This blog will be a good starting point for your TypeScript journey.

Happy Learning

 

1+
Adarsh M

Adarsh M

A soon-to-be engineer and software developer. Curious about advanced tools and Web technologies. Loves to be a part of fast moving technical world.

Add comment