A Journey to Learn Typescript.

kishor_sutradhar_d2503ac4

kishor sutradhar

Posted on November 7, 2024

A Journey to Learn Typescript.

TypescriptHi everyone, I recently began my TypeScript journey and have been making progress through Programming Hero's advanced web development course. I had some basic knowledge of TypeScript but hadn't explored it in depth. My course started with a deep dive into TypeScript. A week has passed, and I've made significant progress in my learning. Here's a simplified overview of the key concepts I've grasped.

TypeScript is like JavaScript, but with superpowers!

TypeScript is a superset of JavaScript that adds optional static typing to the language. This means you can declare the types of variables, function parameters, and return values, which can help catch potential errors early in the development process.
Benefits of Using TypeScript

  • Early Error Detection
  • Improved Code Readability
  • Enhanced Code Reliability
  • Better Code Completion and IntelliSense
  • Large-Scale Project Support

Primitive and non-primitive data type

Primitive data types represent single values and are stored directly in memory. here are some of the primitive data types used in typescript

  • string
  • number
  • boolean
  • undefined
  • null
let name : string = "Kishor";
let age : number = 27;
let isDeveloper: boolen = true;
let x : null = null;
let y: undefined = undefined;
Enter fullscreen mode Exit fullscreen mode

as you can see in the example to assign a type to a variable you have to use the colon ( : ) symbol after defining the variable name and then the type.

Non-Primitive data types, also known as reference types, represent complex data structures and are stored as references to memory locations. TypeScript supports the following non-primitive data types:

  • Object
  • Array
  • tuple
  • function
let Person: {name: string, age : number} = {name: "kishor", age: 27}; //object
let numbers: number[] = [1,2,3,4];
let fruits: string[]= ["apple", "pineapple", "banana"];
let tuple: [string, number, boolean] = ["xyz", 123, true];
function greet(name: string) : any {
  return `hello ${name}`
}
Enter fullscreen mode Exit fullscreen mode

Type Alias

A type alias in TypeScript is a way to give a new name to an existing type. This can make your code more readable and maintainable, especially when dealing with complex types.

// Defining a type alias for a person object
type Person = {
  name: string;
  age: number;
};
// Using the type alias
const person1: Person = {
  name: "Alice",
  age: 30
};
Enter fullscreen mode Exit fullscreen mode

In this example, Person is a type alias that represents an object with name and age properties.
Union and Intersection Types in TypeScript
A union type represents a value that can be one of several types. It's defined using the | operator.
An intersection type combines multiple types into a single type. It's defined using the & operator.

type StringOrNumber = string | number; //Union type
let value: StringOrNumber = "hello";
value = 42;
type Person = {
    name: string;
    age: number;
};
type Address = {
    street: string;
    city: string;
};
type PersonWithAddress = Person & Address;//Intersection type
const personWithAddress: PersonWithAddress = {
    name: "Alice",
    age: 30,
    street: "123 Main St",
    city: "Anytown"
};
Enter fullscreen mode Exit fullscreen mode

never, unknown

The never type represents values that never occur.
The unknown type represents any value. It's safer than the any type because you must perform type checks or assertions before using a value of type unknown.

function error(message: string): never {
    throw new Error(message);
} //the return type is never because there is no data returned.
let value: unknown = "hello";
if (typeof value === "string") {
  let strLength: number = value.length;
}
Enter fullscreen mode Exit fullscreen mode

Type Assertion

Type assertion is a way to tell the TypeScript compiler that you know more about a type than it does. It's a way to explicitly specify the type of a variable

let value: unknown = "hello";
let strLength: number = (value as string).length;
Enter fullscreen mode Exit fullscreen mode

Type guards

Type guards allow you to narrow down the type of a variable based on certain conditions. By checking the type of a variable before accessing its properties or methods, you can avoid potential runtime errors.

  • typeofOperator
  • instanceof Operator
//typeof
function printValue(value: unknown) {
    if (typeof value === "string") {
        console.log(value.toUpperCase());
    } else if (typeof value === "number") {
        console.log(value.toFixed(2));   
    }
}
//instanceof
function printDate(date: unknown) {
    if (date instanceof Date) {
        console.log(date.toISOString());
    }
}
Enter fullscreen mode Exit fullscreen mode

Interfaces in TypeScript

An interface in TypeScript is a blueprint for creating objects with specific properties.

interface Person {
  firstName: string;
  lastName: string;
  age: number;
}
const person1: Person = {
  firstName: "Alice",
  lastName: "Johnson",
  age: 30
};
Enter fullscreen mode Exit fullscreen mode

In this example, the Person interface defines that a person object must have firstName, lastName, and age properties. When creating a person1 object

Generics in TypeScript

Generics are a powerful feature in TypeScript that allows you to create reusable components that can work with different data types.

function identity<T>(arg: T): T {
  return arg;
}
identity<string>(string);
Enter fullscreen mode Exit fullscreen mode

In this example, T is a type parameter. It represents a placeholder for any type. When you call the identity function, you can pass any type of argument, and the function will return the same type.

Constraints in TypeScript

In TypeScript, generic constraints allow you to apply limitations on the types that can be passed as arguments to a generic function or used as type parameters in a generic class or interface.

interface Person {
    name: string;
    age: number;
}
function identity<T extends Person>(arg: T): T {
  return arg;
}
const result  = identity<Person>({
    name: "aa";
    age: 12;
});
Enter fullscreen mode Exit fullscreen mode

here the extends keyword is used to constrain the data

The Keyof Operator

The keyof operator in TypeScript is used to get a union type of all the property names of an object type. This is particularly useful when working with generic types and mapped types.

interface Person {
  name: string;
  age: number;
}
type PersonKeys = keyof Person; // Type: "name" | "age"
Enter fullscreen mode Exit fullscreen mode

Utility types

Pick<T, K>: Picks specific properties from T

type Person = {
  name: string;
  age: number;
  email: string;
}
//Pick<T,K>
type name = Pick<Person, "name">;
type nameAge = Pick<Person, "name" | "age">
Enter fullscreen mode Exit fullscreen mode

Omit<T, K>: Omits specific properties from T

type Person = {
  name: string;
  age: number;
  email: string;
}
//Omit<T,K>
type email= Omit<Person, "name" | "age">;
Enter fullscreen mode Exit fullscreen mode

Partial<T>: Makes all properties of T optional.

interface Person {
    name: string;
    age: number;
}
type PartialPerson = Partial<Person>; // { name?: string; age?: number; }
Enter fullscreen mode Exit fullscreen mode

others like,
Required<T>
Readonly<T>
Record<K, T>

Classes in TypeScript

In TypeScript, classes are defined using the class keyword.

class Person {
    firstName: string;
    lastName: string;

    constructor(firstName: string, lastName: string) {
        this.firstName = firstName;
        this.lastName = lastName;   

    }

    greet() {
        console.log("Hello, my name is " + this.firstName + " " + this.lastName);   

    }
}
Enter fullscreen mode Exit fullscreen mode

Access Modifiers in TypeScript

public The default visibility of class members is public. A public member can be accessed anywhere
protected members are only visible to subclasses of the class they're declared in.
private Members are accessible only within the class.

Static Members in TypeScript

Static members in TypeScript are members (properties and methods) that belong to the class itself, rather than to individual instances of the class.

class MyClass {
    static staticProperty: string = "Static Property";

    static staticMethod() {
        console.log("Static Method");
    }
}
Enter fullscreen mode Exit fullscreen mode

Implementation in TypeScript

In TypeScript, interfaces define a contract for classes to implement. A class that implements an interface must have all the properties and methods declared in the interface. The implements keyword is used

interface Shape {
    area(): number;
}

class Circle implements Shape {
    radius: number;

    constructor(radius: number) {
        this.radius = radius;
    }

    area():   
 number {
        return Math.PI * this.radius * this.radius;   

    }
}
Enter fullscreen mode Exit fullscreen mode

Conclusion:

Those are some of the basic use cases of Typescript that I learned this week. I've learned a bunch of cool stuff, but there's still so much more to discover. TypeScript is constantly evolving, so I am trying to keep up with the latest releases and features and following TypeScript's official documentation and blog for the latest news and best practices. 
Thanks for keeping up with me on my journey.

💖 💪 🙅 🚩
kishor_sutradhar_d2503ac4
kishor sutradhar

Posted on November 7, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related