Skip to content

Latest commit

 

History

History
145 lines (102 loc) · 3.28 KB

Understanding Types.md

File metadata and controls

145 lines (102 loc) · 3.28 KB

Understanding Types

Introduction

Understanding types in TypeScript is fundamental to leveraging the language's static typing features. TypeScript provides a way to describe the shape and behavior of values, making it more robust and maintainable. Let's explore key concepts related to types in TypeScript:

Table of Contents

1. Basic Types:

a. Number:

let age: number = 25;

b. String:

let name: string = "Alice";

c. Boolean:

let isValid: boolean = true;

d. Array:

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

2. Object Types:

a. Object Literal:

let person: { name: string; age: number } = { name: "John", age: 30 };

b. Interface:

interface Person {
    name: string;
    age: number;
}

let employee: Person = { name: "Alice", age: 25 };

3. Union and Intersection Types:

a. Union Types:

let result: number | string = 10;
result = "Success";

b. Intersection Types:

type Name = { firstName: string };
type Age = { age: number };

let personInfo: Name & Age = { firstName: "John", age: 30 };

4. Function Types:

a. Function Parameter and Return Types:

function add(x: number, y: number): number {
    return x + y;
}

5. Generics:

a. Generic Function:

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

let result: number = identity(10);

6. Type Aliases:

a. Creating Custom Types:

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

let coordinates: Point = { x: 1, y: 2 };

7. Type Assertion:

a. Explicit Type Conversion:

let strLength: number = (<string>"Hello").length;

8. Declaration Files (.d.ts):

a. Defining Types for External Modules:

// example.d.ts
declare module "example-library" {
    function myFunction(value: string): number;
}

Understanding these types and concepts allows you to create more expressive and error-resistant TypeScript code. TypeScript's static typing helps catch potential issues during development, making your codebase more robust and maintainable. Choose the appropriate type based on the context and requirements of your code.