[node. js] uses typescript to write Node projects

Source: Internet
Author: User
Tags export class

Original address: http://www.moye.me/2015/04/25/using_typescript/

Into the TypeScript pit for some time, sincerely optimistic, so decided to private plots in the long-winded.

What is it

TypeScript (hereinafter referred to as TS) is a hard-to-launch JavaScript translation language, which means:

    1. It needs to be compiled
    2. TS code will be compiled into JavaScript code

TS is characterized by the provision of modules, classes, interfaces and other types of concepts, to help developers at compile time to locate some of the traditional JavaScript project run-time errors to achieve the so-called "robust components" (it is worth mentioning that TS is the famous Anders Hejlsberg-led projects.

Why

JavaScript is generally considered to be a dynamic type, a weak type of language, and it has great flexibility. As shown below, the type changes are not constrained:

var x = 10;console.log (typeof x);  Result-Numberx = ' Hello '; Console.log (typeof x);  Result-String

So what is the type concept introduced by TS? Consider an example:

I have a function of summation

function sum (x, y) {    return x + y;}

But you can use it too, JavaScript has no opinion, although the result is unreasonable:

SUM (+, ' hello '); Result-100hello

So, we use TS such a qualification, to ensure that the above call is not compiled (the input is number, the return must be number:

function sum (x:number, Y:number): number {    return x + y;}

Because we firmly believe that summing a number and a string is not a sensible requirement--and that the result of sum is credible.

class Example

In Node, because of the power of the flow and the event mechanism, many times we will let our own classes inherit events. The EVENTEMITTER,JS code looks like this:

var events = require (' events '); var util = require (' util '); function MyClass () {   events. Eventemitter.call (this);} Util.inherits (MyClass, events. Eventemitter);

If you're familiar with node's set of theories, it's fine, but actually with TS, you can write more elegant code:

Import events = require (' Events '), Import util = require (' util '); Export class MyClass extends events. eventemitter{    Constructor () {        super ();    }}

specific grammatical specifications here do not explain, interested can refer to the official Specification.

Here is to say that the TS generated JS code is very high quality, the above fragment generated code (the closure of pollution is also taken into account:

var __extends = This.__extends | | function (d, b) {for    (var p in B) if (B.hasownproperty (p)) d[p] = b[p];    function __ () {this.constructor = D;}    __.prototype = B.prototype;    D.prototype = new __ ();}; var events = require (' events '); var MyClass = (function (_super) {    __extends (MyClass, _super);    function MyClass () {        _super.call (this);    }    return MyClass;}) (Events. Eventemitter); exports. MyClass = MyClass;
Use in Webstrom

I have retired Windows development to protect the peace, but also can only talk about the use of Webstorm problems:

First, you have to have a TS compiler

NPM install-g typescript

Then, when you first create a. ts file, Webstorm asks if you want to add watcher to the. ts file so that watcher automatically calls the compiler to compile & build when the file has a save action--my option is "no" : A little bit of the project will use automated building tools such as Grunt/gulp, the compilation will be included as a part of the building, then take grunt as an example, compiling this matter to grunt-ts is more reasonable. Grunt-ts Configuration Example:

TS: {    default: {        src: [' **/*.ts ', '!node_modules/**/*.ts '],        target: ' es5 ',        outDir: '/repo/releases ',        options: {            fast: "Never",            module: "Commonjs",            Sourcemap:false,            Suppressimplicitanyindexerrors:true,            preserveconstenums:true        }}}    

TS has its own set of theories when it comes to the library of import require: it needs a. d.ts file to describe the schema of the referenced library, such as the reference underscore:

Import underscore = require (' underscore ');

Then in the project, there needs to be a underscore.d.ts, which declares such a sentence (for a complete example, refer to Underscore.d.ts:

DECLARE module "Underscore" {export = _;//...}

Then declare a. D.ts in the referenced place and introduce:

<reference path= "Underscore.d.ts"/>

In this way, it can be compiled correctly, and can also get webstorm smart hints. Of course, if you are uncomfortable with this kind of trouble reference, you can skip the TS check directly using the following form without import:

var underscore = require (' underscore ');

In general, well-known third-party libraries can be found in the Definitelytyped project. D.ts, and Webstorm also provides a quick reference:

Downloads TypeScript Community, Preferences-Languages & Frameworks---Libraries stubs, choose what you need Downlo AD & Install:

Reference
    1. TypeScript Handbook:online Version

More articles please visit my blog new address: http://www.moye.me/

[node. js] uses typescript to write Node projects

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.