Home  >  Article  >  Web Front-end  >  A Journey to Learn Typescript.

A Journey to Learn Typescript.

Susan Sarandon
Susan SarandonOriginal
2024-11-08 16:13:02849browse

A Journey to Learn Typescript.Hi 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;

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}`
}

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
};

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"
};

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.

let name : string = "Kishor";
let age : number = 27;
let isDeveloper: boolen = true;
let x : null = null;
let y: undefined = undefined;

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 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}`
}

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
// 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
};

Interfaces in TypeScript

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

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"
};

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 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;
}

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.

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

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.

//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());
    }
}

Utility types

Pick: Picks specific properties from T

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

Omit: Omits specific properties from T

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

Partial: Makes all properties of T optional.

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

others like,
Required
Readonly
Record

Classes in TypeScript

In TypeScript, classes are defined using the class keyword.

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

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.

let name : string = "Kishor";
let age : number = 27;
let isDeveloper: boolen = true;
let x : null = null;
let y: undefined = undefined;

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

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}`
}

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.

The above is the detailed content of A Journey to Learn Typescript.. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn