This is the 12th day of my participation in the August More Text Challenge. For details, see: August More Text Challenge

preface

What is TypeScript? A superset of JavaScript that can be compiled to pure JavaScript. We all know that JavaScript is a dynamically typed language, so it is hard to avoid misthinking when dealing with complex scenarios. TypeScript helps us to do this by using TypeScript’s powerful type system and assertion system for syntax and error checking.

Why do we use TypeScript?

Let’s look at some code:

function double(num) {
    return num * 2;
}
double(1) / / 2
double(2) / / 4
double(3) / / 6
Copy the code

But what happens when our input is no longer of type number because of some upstream branch error? Maybe you say this, this is easy, change the code

function double(num) {
    if (typeofnum ! = ='number') {
        return 'error'
    }
    return num * 2;
}
double(1) / / 2
double(2) / / 4
double(3) / / 6
Copy the code

This works, but there’s a new problem: there are two types of returns!!

So does the caller have to make a judgment every time? This is clearly unreasonable. The code will look like this:

function double(num) {
    if (typeofnum ! = ='number') {
        return 'error'
    }
    return num * 2;
}
const x = double(a)
if (x === 'error') {
    // TODO
} else {
    // TODO
}
Copy the code

Let’s see how TypeScript solves this problem:

function double(num: number) {
    return num * 2;
}
const x = double(a)
Copy the code

According to TypeScript’s type system, if double is passed with a type other than number, an error will be reported at compile time. The code will not run, and there will be no subsequent runtime errors.

This pre-check mode can greatly reduce the mental burden of developers. Some of the irregularities in the code, the data structure changes in the API, can be directly verified through the type system.

The base type

TypeScript not only has all the basic types of JavaScript, but it also has some additional support for the following types: Boolean, number, string, [], the Tuple, enum, any, void, null, and undefined, never, Object.

let isDone: boolean = false;

let decLiteral: number = 6;

let name: string = "bob";

let list: number[] = [1.2.3];

let x: [string.number];

enum Color {Red, Green, Blue}

let notSure: any = 4;

function warnUser() :void {
    console.log("This is my warning message");
}

let u: undefined = undefined;
let n: null = null;

// A function that returns never must have an unreachable endpoint
function error(message: string) :never {
    throw new Error(message);
}

declare function create(o: object | null) :void;
Copy the code

summary

Today’s focus is on TypeScript’s type system, which helps you quickly locate and find problems. For the project is not aggressive, can be mixed JS+TS mode.

But in order to use it on a large scale within a team, you still need the cooperation of other members, after all, there are certain thresholds for using a new technology.