"TypeScript" TypeScript learning 4--Module

Source: Internet
Author: User
Tags export class

Front-end data validation is a big part of improving the user experience, and when you're learning about previous knowledge, we'll probably write the following code:

interface Stringvalidator {isacceptable (s:string):Boolean;}varLettersregexp =/^[a-za-z]+$/;varNumberregexp =/^[0-9]+$/; class Lettersonlyvalidator implements Stringvalidator {isacceptable (s:string) {returnLettersregexp.test (s); }}class Zipcodevalidator implements Stringvalidator {isacceptable (s:string) {returnS.length = = 5 &&Numberregexp.test (s); }}//Some samples to tryvarstrings = [' Hello ', ' 98052 ', ' 101 '];//validators to usevarValidators: {[s:string]: stringvalidator;} ={};validators[' ZIP code '] =Newzipcodevalidator (); validators[' Letters only '] =Newlettersonlyvalidator ();//Show Whether each string passed each validatorStrings.foreach (s = = {     for(varNameinchvalidators) {Console.log (' ' + S + ' "' + (validators[name].isacceptable (s)? ' matches ': ' does not match ') +name); }});

So what's the biggest problem with this code? One is not reusable, validating the encapsulation and validation process in the same file, the validated encapsulation is already reusable. The other is that the interface and the two implemented classes are directly attached to the global variable, and if there is more than one, the whole global variable will be polluted.

Modularity was born to solve this problem.

module Validation {Export interface Stringvalidator {isacceptable (s:string):Boolean; }    varLettersregexp =/^[a-za-z]+$/; varNumberregexp =/^[0-9]+$/; Export class Lettersonlyvalidator implements Stringvalidator {isacceptable (s:string) {returnLettersregexp.test (s); }} Export Class Zipcodevalidator implements Stringvalidator {isacceptable (s:string) {returnS.length = = 5 &&Numberregexp.test (s); }    }}//Some samples to tryvarstrings = [' Hello ', ' 98052 ', ' 101 '];//validators to usevarValidators: {[s:string]: validation.stringvalidator;} ={};validators[' ZIP code '] =Newvalidation.zipcodevalidator (); validators[' Letters only '] =Newvalidation.lettersonlyvalidator ();//Show Whether each string passed each validatorStrings.foreach (s = = {     for(varNameinchvalidators) {Console.log (' ' + S + ' "' + (validators[name].isacceptable (s)? ' matches ': ' does not match ') +name); }});

We use the Module keyword to define modules, using the Export keyword to make our interfaces, classes, and other members visible outside the module.

In this way, only the module name is attached to the global variable, minimizing the pollution of global variables.

    • Separating modules into multiple files

As our project expands, it is impossible for our code to be written only in one file. To better maintain the project, we put specific features into a file and then load multiple functions to implement the functionality we want. Now we'll split the above code into multiple files.

Validation.ts

module Validation {    export interface Stringvalidator {        boolean;    }}

Lettersonlyvalidator.ts

// /<reference path= "Validation.ts"/> module Validation {    var lettersregexp =/^[a-za-z]+$/;    Export class Lettersonlyvalidator implements Stringvalidator {        isacceptable (s:string) {            return< /c15> Lettersregexp.test (s);     }}

Zipcodevalidator.ts

// /<reference path= "Validation.ts"/> module Validation {    var numberregexp =/^[0-9]+$/;    Export class Zipcodevalidator implements Stringvalidator {        isacceptable (s:string) {            return S.length = = = 5 && numberregexp.test (S    ); }}

Test.ts

///<reference path= "Validation.ts"/>///<reference path= "Lettersonlyvalidator.ts"/>///<reference path= "Zipcodevalidator.ts"/>//Some samples to tryvarstrings = [' Hello ', ' 98052 ', ' 101 '];//validators to usevarValidators: {[s:string]: validation.stringvalidator;} ={};validators[' ZIP code '] =Newvalidation.zipcodevalidator (); validators[' Letters only '] =Newvalidation.lettersonlyvalidator ();//Show Whether each string passed each validatorStrings.foreach (s = = {     for(varNameinchvalidators) {Console.log (' ' + S + ' "' + (validators[name].isacceptable (s)? ' matches ': ' does not match ') +name); }});

Create more than four files in the project, then we compile the project, if our code is written correctly, it can be compiled through. In addition, we can see the following three files at the beginning of a similar to C # document comments, this is to tell the TypeScript compiler that the file depends on which files, if the dependent file does not exist, the compilation will not pass. Of course, we do not write is also possible, but the compiler will not be compiled to help us check, generally speaking, or recommended to write on.

In addition, we need to be aware of the good order when referencing compiled JavaScript files. For example, in the code above, we have already referenced this in Html code.

<Scriptsrc= "Validation.js"type= "Text/javascript" /><script src="Lettersonlyvalidator.js"type="Text/javascript" /><script src="Zipcodevalidator.js"type="Text/javascript" /><script src="Test.js"type="Text/javascript" />
    • External modules

In the above way, the browser will load 4 JavaScript. But at some point, we don't need to use all of them, we should load on demand. So how to do it in TypeScript, it's very simple, just need a little modification on the line.

Validation.ts

Export interface Stringvalidator {    boolean;}

Lettersonlyvalidator.ts

Import validation = require ('./validation '); var lettersregexp =/^[a-za-z]+$/; Export class Lettersonlyvalidator implements validation. Stringvalidator {    isacceptable (s:string) {        return  lettersregexp.test (s);    }}

Zipcodevalidator.ts

Import validation = require ('./validation '); var numberregexp =/^[0-9]+$/; Export class Zipcodevalidator implements validation. Stringvalidator {    isacceptable (s:string) {        return s.length = = = 5 &&  Numberregexp.test (s);    }}

Test.ts

Import validation = require ('./validation ')); Import Zip= require ('./zipcodevalidator ')); Import Letters= require ('./lettersonlyvalidator '));//Some samples to tryvarstrings = [' Hello ', ' 98052 ', ' 101 '];//validators to usevarValidators: {[s:string]: validation. Stringvalidator; } ={};validators[' ZIP code '] =Newzip. Zipcodevalidator (); validators[' Letters only '] =NewLetters. Lettersonlyvalidator ();//Show Whether each string passed each validatorStrings.foreach (s = = {     for(varNameinchvalidators) {Console.log (' ' + S + ' "' + (validators[name].isacceptable (s)? ' matches ': ' does not match ') +name); }});

After you finish modifying, compile ... Not through!

Crossing may think I hang Dad, hard to knock such a big paragraph after, unexpectedly compiled do not pass. Here, let's first talk about the two specifications for module loading.

CommonJS Specification:

The goal of CommonJS is to implement a standard library similar to Python, Ruby and other languages. And NodeJS is using this specification.

var m = require (' mod '= m.something + 1;
AMD Specifications:

Because the load implemented by the CommonJS specification above is synchronous, in fact, our browser needs more asynchronous loading, so the AMD specification comes into being.

function (require, exports, m) {    = m.something + 1;});

So what kind of specification does TypeScript use? The answer is both, and you need to choose one of them.

Go back to our project and modify the project properties.

Change this to AMD or CommonJS, then you can compile it.

    • Export =

In the above code, we export the root of the module is a file, so we need to write a zip. Zipcodevalidator This form, why not simplify it? It's better to use Zipcodevalidator directly. Export = can help us to do this thing.

Validation.ts

Export interface Stringvalidator {    boolean;}

Lettersonlyvalidator.ts

Import validation = require ('./validation '); var lettersregexp =/^[a-za-z]+$/; class Lettersonlyvalidator implements validation. Stringvalidator {    isacceptable (s:string) {        return  lettersregexp.test (s);     = Lettersonlyvalidator;

Zipcodevalidator.ts

Import validation = require ('./validation '); var numberregexp =/^[0-9]+$/; class Zipcodevalidator implements validation. Stringvalidator {    isacceptable (s:string) {        return s.length = = = 5 &&  Numberregexp.test (s);     = Zipcodevalidator;

Test.ts

Import validation = require ('./validation ')); Import Zipvalidator= require ('./zipcodevalidator ')); Import Lettersvalidator= require ('./lettersonlyvalidator '));//Some samples to tryvarstrings = [' Hello ', ' 98052 ', ' 101 '];//validators to usevarValidators: {[s:string]: validation. Stringvalidator; } ={};validators[' ZIP code '] =Newzipvalidator (); validators[' Letters only '] =Newlettersvalidator ();//Show Whether each string passed each validatorStrings.foreach (s = = {     for(varNameinchvalidators) {Console.log (' ' + S + ' "' + (validators[name].isacceptable (s)? ' matches ': ' does not match ') +name); }});
    • Alias
module Shapes {    Export module polygons {Export        class Triangle {}        Export class Square {}    =  shapes.polygons; var New // same as ' new Shapes.Polygons.Square () '

So write import, the following code can be abbreviated. It is important to note that the modules introduced by require are not supported.

    • DECLARE keywords

Sometimes we need to define global variables, then we need to add declare keywords.

DECLARE ver myString;

Then the myString variable is global. This function is useful when defining global modules.

"TypeScript" TypeScript learning 4--Module

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.