Logo

dev-resources.site

for different kinds of informations.

Introduction to TypeScript

Published at
7/24/2024
Categories
ts
javascript
types
Author
__khojiakbar__
Categories
3 categories in total
ts
open
javascript
open
types
open
Author
14 person written this
__khojiakbar__
open
Introduction to TypeScript

TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. It adds static types to your code, making it easier to catch errors during development.

Setting Up TypeScript
First, let's set up TypeScript:

  1. Install TypeScript globally using npm:
npm install -g typescript
Enter fullscreen mode Exit fullscreen mode
  1. Initialize a TypeScript project:
tsc --init
Enter fullscreen mode Exit fullscreen mode
  1. Compile TypeScript:

To compile a TypeScript file (.ts), run:

tsc filename.ts
Enter fullscreen mode Exit fullscreen mode

Basic Types

Let's start with some basic types and funny examples.

1. Primitive Types

  • String
let greeting: string = "Hello, TypeScript!";
console.log(greeting); // Hello, TypeScript!
Enter fullscreen mode Exit fullscreen mode
  • Number
let age: number = 42;
console.log(`I'm ${age} years old!`); // I'm 42 years old!
Enter fullscreen mode Exit fullscreen mode
  • Boolean
let isHappy: boolean = true;
console.log(`Am I happy? ${isHappy}`); // Am I happy? true
Enter fullscreen mode Exit fullscreen mode

Imagine a robot that can only understand specific types:

let robotName: string = "RoboCop";
let robotAge: number = 100;
let isRobotFriendly: boolean = true;

console.log(`Meet ${robotName}, who is ${robotAge} years old. Friendly? ${isRobotFriendly}`); 
// Meet RoboCop, who is 100 years old. Friendly? true
Enter fullscreen mode Exit fullscreen mode

2. Array

TypeScript arrays can hold only one type of data:

let fruits: string[] = ["Apple", "Banana", "Cherry"];
console.log(fruits); // ["Apple", "Banana", "Cherry"]
Enter fullscreen mode Exit fullscreen mode

A cat organizing its toy collection (only balls):

let catToys: string[] = ["Ball1", "Ball2", "Ball3"];
console.log(catToys); // ["Ball1", "Ball2", "Ball3"]
Enter fullscreen mode Exit fullscreen mode

3. Tuple

Tuples allow you to express an array with a fixed number of elements whose types are known:

let myTuple: [string, number];
myTuple = ["Hello", 42]; // OK
console.log(myTuple); // ["Hello", 42]
Enter fullscreen mode Exit fullscreen mode

Imagine a super-secret agent with a codename and an ID number:

let agent: [string, number] = ["Bond", 007];
console.log(agent); // ["Bond", 007]
Enter fullscreen mode Exit fullscreen mode

Functions

TypeScript allows you to specify the types of parameters and return values of functions.

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

console.log(add(5, 3)); // 8
Enter fullscreen mode Exit fullscreen mode

A chef with a magic spoon:

function mixIngredients(ingredient1: string, ingredient2: string): string {
    return `${ingredient1} mixed with ${ingredient2}`;
}

console.log(mixIngredients("Flour", "Sugar")); // Flour mixed with Sugar
Enter fullscreen mode Exit fullscreen mode

Interfaces

Interfaces define the structure of an object.

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

let user: Person = {
    name: "Alice",
    age: 30
};

console.log(user); // { name: "Alice", age: 30 }
Enter fullscreen mode Exit fullscreen mode

A talking dog with a special ID card:

interface Dog {
    name: string;
    breed: string;
}

let talkingDog: Dog = {
    name: "Scooby-Doo",
    breed: "Great Dane"
};

console.log(talkingDog); // { name: "Scooby-Doo", breed: "Great Dane" }
Enter fullscreen mode Exit fullscreen mode

Classes

TypeScript classes are a blueprint for creating objects with initial values and methods.

class Animal {
    name: string;

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

    move(distance: number = 0) {
        console.log(`${this.name} moved ${distance} meters.`);
    }
}

let dog = new Animal("Dog");
dog.move(10); // Dog moved 10 meters.
Enter fullscreen mode Exit fullscreen mode

A superhero class:

class Superhero {
    name: string;

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

    saveTheCat() {
        console.log(`${this.name} saved the cat!`);
    }
}

let hero = new Superhero("Batman");
hero.saveTheCat(); // Batman saved the cat!
Enter fullscreen mode Exit fullscreen mode

Enums

Enums allow us to define a set of named constants.

enum Direction {
    Up,
    Down,
    Left,
    Right
}

let move: Direction = Direction.Up;
console.log(move); // 0
Enter fullscreen mode Exit fullscreen mode

A traffic light system:

enum TrafficLight {
    Red,
    Yellow,
    Green
}

let light: TrafficLight = TrafficLight.Green;
console.log(light); // 2
Enter fullscreen mode Exit fullscreen mode

Conclusion

You've just had a whirlwind tour of TypeScript, from basic types to more advanced feature like enums. With these examples, you should have a good starting point to further explore and use TypeScript in your projects.

Feel free to ask if you have any specific questions or need more funny examples for any part of TypeScript!

types Article's
30 articles in total
Favicon
Matanuska ADR 009 - Type Awareness in The Compiler and Runtime
Favicon
Matanuska ADR 007 - Type Semantics for Primary Types
Favicon
Opkey Highlights Importance of Staying Informed About Testing Types for Enhanced Quality Assurance
Favicon
Understanding Next.js and TypeScript Tutorial
Favicon
Python Has Types, They Help
Favicon
YAGNI For Types
Favicon
TypeScript's Lack of Naming Types and Type Conversion in Angular
Favicon
Six Alternatives to Using any in TypeScript
Favicon
Some Types - Part 1
Favicon
Top 9 Essential Utility Types in TypeScript
Favicon
Introduction to TypeScript
Favicon
Error Types in JS
Favicon
Prefer strict types in Typescript
Favicon
Having a type system is more productive
Favicon
Javascript Data Types
Favicon
Simplifying Complex Type Display in TypeScript and VS Code
Favicon
Key Software Testing Types Every QA Needs to Know
Favicon
Understanding and Implementing Type Guards in TypeScript
Favicon
Choosing the Right Database: A Comprehensive Guide to Types and Selection Criteria
Favicon
TypeScript Template Literal Types: Practical Use-Cases for Improved Code Quality
Favicon
Language types for integration safety
Favicon
The cost of types
Favicon
Discriminated Unions
Favicon
Using variant types in ReScript to represent business logic
Favicon
Building React Components Using Unions in TypeScript
Favicon
How to Typescript to JSON with Butlermock
Favicon
Integration Testing Types: A Brief Guide
Favicon
The Benefits of Static Typing: A Developer's Perspective
Favicon
React - Uncaught TypeError: Cannot read properties of undefined (reading 'lat')
Favicon
Conjuring TypeScript's Magic with Mapped Types

Featured ones: