function outcome (value) {}
Copy the code

This is a standard JavaScript function. This is how every front-end developer (you’d think) writes their functions. Just like you did that night, you paid the price for your madness. But the cost is just a parameter, it exists, but its reality is unknown to you. It could be a dot on his body a week later, or a word on his tombstone a year later. Uncertainty is certain, the unknown is painful, and stimulation is inevitable. You can’t sleep at night, and your mind is constantly burdened with the mathematical expectation of multiplying outcomes by weights.

You decide to set up unit tests, but vanity leads you to interview a trusted colleague, a thug whose zen is enough to make you sick. He half opened his eyes in meditation, and he told you

function outcome (value? : DefinetlyNotADisease) : VeryVeryMinorResult {}Copy the code

You like to think, but most of them are questions about whether a zebra is a horse or a donkey. The zen master’s words open a door to your inner world. You think on the way home. Whether your pain comes from not knowing the outcome or not knowing the outcome. Recall the Zen master’s words, “certainty is the basic language of engineering,” as if understood, and “unknown unknowns can be mistaken for knowns through ignorance.” You’re thinking, what the hell is that? But you did it anyway.

Forget your fears and you begin to feel vaguely resentful and sleepy.

A dream: Not knowing what is what

>npm install -g typescript

>tsc –target “ES5”

After a perfect night’s sleep, you feel rejuvenated, and you start to remember your recent experiences. You start to wonder if you are you. Are you a stand-in killed by TypeScript, or are you sublimated? You don’t want to be another you, a dead you or learn to be another you. At this thought, the confusion of whether zebras are horses or donkeys rises to the throat and even to the sinuses. And so you are back before your fellow-servants, who are consecrated on their high walls. This time he says that JavaScript is a subset of TypeScript and can be considered a type of TS. And make a move

#! /usr/bin/env node// does nothing but change the extension. Let fs = require('fs'); const lookfor = 'src'; function recurr (lookfor) {fs.readdir(lookfor, (err, files) => {files.forEach(a => {let path = lookfor + '/' + a,f = fs.statSync(path); if (f.isDirectory()) {recurr(path); } else if (a.match(/\.js$/)) {fs.renameSync(path, path.replace(/\.js$/, '.ts')); }}); }); }recurr(lookfor); console.log('done! simple like that! ')Copy the code

“No line of code to change, no line of code to change, no line of code to change (except function outcome)”, the Zen master turned up the volume, reverb, synthesizer, echo the least philosophical sentence three important times. Suddenly you know who you are. Who is just a few more new possibilities, no matter who resists you, who can accept themselves. Satisfied, you start galloping home like a horse or a donkey. However, you still have a lot of confusion and can’t get rid of it. Your colleagues feel that they have been talking nonsense lately and that you might be able to join the wall. They drift away from you.

You know you haven’t changed, and you start adding type declarations to the original code. The type declarations are extremely simple, but at the same time they don’t touch the original code logic at all:

Function outcome(val: Even) : void {function outcome(val: Even); The return value is void let temp: string; // let ties: number; Tombs: Array<number> = [1]; // Array of type number let mount: Observeable<string>; // onNext string Observeable let what: any; // The JavaScript variable before the type is any; }Copy the code

You always know ahead of time. Know many things in advance. You start to wonder if it’s madness to write code once and run it. You don’t have to go back and forth between documents, you don’t have to worry about spelling, you don’t have to worry about making changes to things that you copy, you start to know in advance that you can’t know in advance.

In the next few days you configure tsconfig.json and your editor plugin, and smart alerts will fly to you in real time. You start tweaking tsConfig with interest.

You find that Babel has built in to compile ES5, ES6, ES7, and an unintelligible ESNext.

The Module specification also supports Node commonJS, ES7 import, AMD, SYSTEM, UMD, ES2016, ESNext.

{  
  "compilerOptions": {
    "outDir": "./dist/",
    "noImplicitAny": true,
    "sourceMap": true,
    "module": "commonjs",/* AMD system UMD ES2015 ES2016 ES2017 ESNext */
    "target": "es2015", /* ES3 ES5 ES6 ES2015 ES2016 ES2017 ESNext */
    "jsx": "react",
    "allowJs": true
  }
}
Copy the code

The code lit up. Microsoft offers an extensive editor TS plugin that compiles real alerts in real time, unlike Sublime Text’s default word alerts (and Zen Master himself).

Microsoft offers a number of TypeScript plug-ins for major editors. True content reminder

TypeScript semantics can distinguish between bad references, bad arguments, and bad assignments. Cooperation is no longer a matter of meeting, meeting, meeting

Gradually, you start killing objects who have been hiding behind Any

let enumDom : {[key: string] : number} = {}; // Key is string, value is object of number; Class DLabel extends DeafElement{// virtual class, direct as type use width: number; height: number; text: string; fontsize: number; } enum DNodes{// A special type of the enumeration. Net = 'net', col = 'col ', from = 'from', to = 'to', place = 'place', trans = 'trans', Sition = 'sition'} interface Point{// Interface x: number, y: number}Copy the code

In the process, your code is becoming more and more formal, and you need to continue to eliminate any and cast everything on the parent and child classes.

For example, document.getelementById returns a generic HTMLElement. It’s cast as HTMLCanvasElement so the post knows about the getContext method. The sand-fleshed watermelons have no idea.

Variables can be Cast polymorphic before, in TSX is replaced with as after

You notice that your colleagues are starting to use some of the ES7 toys. Of course you already use this and TsConfig decides how to compile it.

"use strict"; // When ES7 features are assigned to ES6 by tsconfig's target, TSC will use the Iteration & Generation feature in ES6 to compile the implementation // Who knows what target will do in ES5. In short, Is the var __awaiter = (this && enclosing __awaiter) | | function (thisArg _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); };Copy the code

With that done, your development speed has rocketed like a set of supersonic swallows through the clouds, thanks to improved accuracy and alert auxiliary inputs.

You find that there are always external JS exchanges in your project, and these JS have type definitions… Zen master brain waves come, you need some NPM packs.

Package. Json:

..." DevDependencies ": {" @ types/koa" : "^ 2.0.39", "@ types/lodash" : "^ 4.14.77", "@ types/node" : "^ 8.0.33"},...Copy the code

Inside them are some *.D. ts files

@ types/react the react types

Some NPM packages developed by TS and compiled into JS already integrate d.ts type declarations



The content of the Rx

TS code can start by referring to JS as if it were JS, and TS as if it were TS.

#include <stdio.h>

Your mind jumps to some young age, everything seems like a different age, but there are not as far away. You feel the shrines open to you, but there is an unexpected lack of some kind of human breath. You start spontaneously writing all your projects using TS, and you get used to submitting @types packages to open source libraries that lack type definitions. With these rapid changes you write more and more of the underlying libraries for your company and get referenced more and more.

From behind the dark clouds in the distance, you can see the sun shining. You can see the rain falling from the sky. They are arranged in vertical dark stripes of varying shades, while the bright sky outside is dazzling. The wind on my face seemed to send some trace of muddy water and a chaotic smell.

Suddenly you wake up and realize it’s been three years. Zen master has been caught, for a long time did not write code was forcibly fired. TS has grown in popularity and maturity. Younger colleagues are also talking about a new feature. Everything is different from three years ago. You’ve already seen closure Compiler and other type-checking tools. You rub your eyes, and you don’t recognize yourself or your code. You realize you might be the zen master you once were. You sit on his old favorite bay window mat and stare into the sky. Even now you can’t tell if this is the moment or three years ago. You begin to think that the unknown unknown is mistaken for the known because of ignorance and that you are an idiot. Suddenly at this time, you are clearly heard with takeout of the two small colleagues, they chat while walking through the mouth to discuss “zebra is white horse black stripe, or black horse white stripe?” At this point, you cut right in and answered them:

No, it’s a donkey.