Giter VIP home page Giter VIP logo

typescript-101's Introduction

What is TypeScript ?

TypeScript is

  • an object-oriented programming language developed and maintained by Microsoft
  • a superset of JavaScript and contains all of its elements
  • built on javascript even though it uses the .ts extension instead of the .js extension
  • easily compiled to plain javascript via a TypeScript compiler


Why consider TypeScript ?

  • Static typing makes large scale applications more robust and less prone to bugs.
  • OOP concepts such as Classes, Interfaces, Inheritance etc are supported.
  • Many frameworks support TypeScript so it is easy to adopt it for your development.

Figures of Interest


Source: 2021 Developer Survey

In the 2021 Developer Survey by Stack Overflow, TypeScript ranked significantly above JavaScript in the "Loved vs Dreaded" poll.
In fact, it ranked near the top among programming languages.


Source: State of frontend 2022

In the State of frontend 2022 survey, there is strong opinion expressed in the continued and rising popularity of TypeScript


Source: State of JavaScript 2021

In the State of JavaScript 2021 survey, compared to other languages that compile to JavaScript, TypeScript is polled as the clear choice.


How TypeScript does it?


Static Typing

TypeScript restricts the mixing of data types. Errors would be thrown if the restrictions are violated.

Basic types

Primitive types such as boolean, float, integer and string can be declared and type checked at compile time.

let isTeacher: boolean = true;
let salary: number = 90000;
let name: string = "Zac";

isTeacher = false;         // ok
salary = "one million";   // number type assigned to string will have error
name = 888;               // string type assigned to number will have error  

Array & Tuple

Likewise, array & tuple can be type checked

let ages: number[] = [32, 45, 57];                // array can be declared this way
let joined: Array<number> = [2020, 2013, 2009];   // array can also be declared this way

let graduated:[string, number];                   // tuple allows elements of different types
graduated = ["sep", 2008];                        // ok
graduated = [2007, 2008];                         // this will have error

Any type

There are times where the application deals with data where the type is not available beforehand or only available during runtime.
The any type declaration will allow typechecking to be bypassed.

function getStudentRecord(id: string): any;    // example of a function declaration
let record1 = getStudentRecord("P1001");       // this invocation is ok
let record2 = getStudentRecord(1001);          // this invocation will have error

From the declaration it is clear to see that the function expects a parameter id of type string and will return a value of type any.
While this opt-out checking grants convenience, type-safety is no longer enforced.
The tradeoff here should be made with caution and it is recommended to define your own type eventually.


Union type

Union type means it can be one of several types. The | is used to define union type.

let admissionId: string | number;       // union: expect this variable to be of either type string or number

Other types

Besides the above commonly used types, there are other pre-defined types such as void, undefined, unknown, null, never
An in-depth documentation of the types can be referenced at the offical website


OOP Features

Custom types can be defined to meet your own needs via OOP features like interfaces and classes.
The variables of these types are also type checked.

Interface

interface Teacher {
    name: string;
    isFulltime: boolean;
    email?: string;
}
let teacher: Teacher;
teacher = {name:'Amy', isFullTime: true};   // this is ok even without email

The Teacher interface is a custom defined type. The ? makes the email property optional so the teacher variable can be assigned either with or without it.


Class

class Student {
    public fullname: string;                                // A public property
    private householdIncome: number;                        // A private property

    constructor(studentName: string, income: number) {
        this.fullname = studentName;
        this.householdIncome = income;
    }

    public getHouseholdIncome(): number {
        return this.householdIncome;
    }
}

let newStudent:Student = new Employee('Danny', 5000);       // instantiate with constructor
let familyIncome:number = newStudent.getHouseholdIncome();  // invocation ok
familyIncome = newStudent.householdIncome;                  // private property cannot be accessed directly so there will be error
let studentName:string = newStudent.fullname;               // public property can be accessed directly so ok  

Variables can be instantiated via the constructor with the new keyword.
Class properties can be declared with access modifiers to control accessbility.

More details of TypeScript's OOP features can be referenced here


Basic Setup


TypeScript can be easily setup and configured in a few simple steps.

npm install --save-dev typescript

In a nodeJS project, install the typescript npm module as a dev dependency.


npx tsc --init

This creates a config file tsconfig.json that is initialized with some default options.


{
  "compilerOptions": {
    "target": "es5",                          
    "module": "commonjs",                    
    "lib": ["es6"],                     
    "allowJs": true,
    "outDir": "build",                          
    "rootDir": "src",
    "strict": true,         
    "noImplicitAny": true,
    "esModuleInterop": true,
    "resolveJsonModule": true
  }
}

This is an example of the config file.
This file defines the compiler options to transpile typescript to javascript.
The full list of options configurable can be referenced at the typescript website


TypeScript & Frameworks


import express from 'express';
const app = express();
const port = 5000;

app.get("/", (req, res) => {
  res.send("First TypeScript Project");
});

app.listen(port, () => {
  return console.log(`Server listening at http://localhost:${port}`);
});

This could be a .ts file to run a simple server.


npx tsc

This will compile the typescript in the .ts file to javascript. Then the server code can be run.
More information about the setup can be referenced here.
A more robust setup can be referenced here.

As seen above, typescript can be used together with minimal back-end frameworks like Express & Koa, or opinionated frameworks like NestJS & loopback.


Popular front-end frameworks such as ReactJS, AngularJS & VueJS can already be programmed using TypeScript.
The use of TypeScript is also recommended for large scale development.

Framework Documentation
ReactJS
AngularJS
VueJS

typescript-101's People

Contributors

omnisoho avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.