Why TypeScript?

TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. Any browser. Any host. Any OS. Open Source. ———— TypeScript’s official website

1. Type error detected at first time

According to Rollbar, the top 10 types of errors in front-end projects are as follows:

Seven of these are typeErrors:

  • Cannot read property 'xxx' on undefined: XXX property cannot be read from undefined, usually in A.B.C.
  • 'undefined' is not an object:undefinedIs not the object
  • null is not an object: NULL is not an object
  • 'undefined' is not a function:undefinedIt’s not a function. It usually occurs ina.b.c()In the case.
  • Object doesn't support property
  • Cannot read property 'length': cannot read'length'Property that is expected to be an array, but the actual type of the variable is not an array.
  • Cannot set property of undefined: can’t giveundefinedSet properties.

In addition to the seven TypeErrors, there is also a ReferenceError:

  • 'xxx' is not defined: XXX is not defined.

There is also a RangeError:

  • In JS, an array out of bounds does not raise a RangeError, but some functions do

Hey, hey, don’t these mistakes look familiar?

Because JavaScript is such a flexible language, these errors are often not discovered until the code is running.

2. Smart tips

When using JavaScript, the editor tends to have limited intelligent hints, such as a reminder of the variables you recently entered.

But with TypeScript, knowing what type a variable is currently, the editor can prompt you for all of its properties after type derivation, as well as prompt and validate function arguments.

In addition, you can also write your own.d.ts declaration file for generic JavaScript projects to gain type derivation capabilities.

Other advantages are not discussed here…

Above all, using TypeScript in your projects can greatly improve your productivity and reduce the number of type errors.

At the beginning of the TypeScript experience

Since the current framework in the business project uses vue.js, the 2.x version is not known to support TypeScript very well, so I decided to try out a tool library project first.

Language learning

Slightly, this kind of information is very much, here will not repeat…

The project architecture

  • Project Entrance:src/index.tsNo substance, all of itexport * from '... '(Both are pure functions)
  • Actual code: put in different files according to utility functions, for example
    • String (string related)
    • Env (Environment detection)
    • Url (link address)
    • .
  • Unit tests:test/
  • Document Contents:docs/

Note: The sideEffects field in package.json should be written as false to make it easier to tree-shaking business code when packaging.

Related tool chain

One of the reasons I’ve been on the fence about TypeScript is that the toolchains aren’t quite there yet. But now it’s pretty clear:

  • 1. Code translationbabel(TypeScript and Babel: a beautiful marriage)

Both TypeScript and Babel can convert your ES6+ code to ES5.

But before Babel V7, linking two independent compilers (TypeScript and Babel) together wasn’t easy. The compilation process becomes: TS > TS Compiler > JS > Babel > JS (again).

Now install @babel/preset-typescript so you can pair Babel and typescript perfectly.

  • 2. Code revieweslint(The future of TypeScript on ESLint)

Eslint lint lint lint lint lint Lint Lint Lint Lint Lint Lint Lint lint lint lint lint lint lint lint lint lint lint lint lint lint lint lint lint lint lint lint lint lint lint lint lint lint lint lint lint lint lint lint lint lint lint lint lint lint lint lint lint lint

  • Unit testingjest([RFC] Migrate Jest to TypeScript #7554)

Facebook jest and Yarn (YARN’s Futurev2 and Beyond #6953) are ditching their own Flow for TypeScript

  • 4. Code packagingrollup(Rollup was rewritten in TypeScript by the end of ’17)

Rollup uses rollup-plugin-typescript, but rollup-plugin-typest2 is selected in the project.

Transformation process

  • Installing various dependencies
  • Configure the various configuration files (ESLint, Babel, CommitLint, JEST), most importantlytsconfig.json
  • Source file name suffixes by.jsto.ts(Single test file is also changed)
  • Then TypeScript’s static code type checking will tell you what’s wrong
  • Change the code as you see fit, or comment it with ignore (and sometimes even change the tsconfig configuration)

The document

Documentation standards

TypeScript has an official documentation standard, TSDoc, based on JSDoc.

export class Statistics {
  /** * Returns the average of two numbers. * * @remarks * This method is part of the {@link core-library#Statistics | Statistics subsystem}. * * @param x - The first input number * @param y - The second input number * @returns The arithmetic mean of `x` and `y` * * @beta */
  public static getAverage(x: number, y: number) :number {
    return (x + y) / 2.0; }}Copy the code

Generating documentation

That led me to TypeDoc, an automated document website generator. But all this stuff does is read the source code and then duang it up and generate a bunch of pages.

While this solves document generation, it does not allow you to preview the document in real time at development time.

Automatically generate

0. Failed attempts: Combine with Vuepress

Because TypeDoc can export MD files, I tried to combine it with VuePress. However, because TypeDoc is generated by clearing all files in the target directory, it can be a bit of a hassle (like making a plug-in).

1. The worst option: manually trigger document generation

Nothing to say, for students with perseverance.

2. Middle strategy: monitor the change of source files, automatically trigger the document generation

The document page can be generated automatically, but the page will not be refreshed automatically when previewing.

3. Best option: Automatically generate documents and refresh pages with Webpack, gulp and Grunt (there are typeDoc plug-ins for all three)

When it comes to automatically refreshing pages during development, browser-sync naturally comes to mind.

  • Although Webpack can do anything, but kill chicken how to use a knife
  • Grunt is a bit behind The Times
  • Gulp has worked on this before, so it’s a good time to add this little requirement

Gulpfile.js (gulpfile.js, gulpfile.js)

const gulp = require('gulp')
const typedoc = require('gulp-typedoc')
const browserSync = require('browser-sync').create()

const runTypeDoc = (a)= > gulp
    .src(['src'])
    .pipe(typedoc({
        out: './docs'.// Export * from '... 'There's no need to export the document
        exclude: 'src/index.ts'.tsconfig: 'tsconfig.json',}))const reload = (done) = > {
    browserSync.reload()
    done()
}

const runBrowserSync = (done) = > {
    browserSync.init({
        server: {
            baseDir: './docs',
        },
    })
    done()
}

const watch = (a)= > gulp.watch(
    ['README.md'.'src/*.ts'],
    gulp.series(runTypeDoc, reload)
)

gulp.task('default', gulp.series(runTypeDoc, runBrowserSync, watch))
Copy the code

To be continued…

The resources

  • The TypeScript’s official website
  • What pain points does TypeScript address? – Answer by JustJavac – Zhihu
  • @babel/preset-typescript
  • TypeScript and Babel: a beautiful marriage
  • The future of TypeScript on ESLint
  • Migrate the repo to ESLint #30553
  • [RFC] Migrate Jest to TypeScript #7554
  • Yarn’s Future – v2 and beyond #6953
  • Rollup was rewritten in TypeScript by the end of ’17
  • rollup-plugin-typescript2
  • tsdoc
  • typedoc
  • browser-sync
  • Typedoc plug-in
  • rollbar