CodesJava

Easy learning with example program codes

typescript namespace multiple files

TypeScript NameSpace:

TypeScript namespace is a way to organize your code. Internal modules in typescript are now referred to namespaces. The namespace keyword is used to define a namespace.

Syntax:

namespace NameSpaceName { 
   export interface IInterfaceName { }  
   export class ClassName { }  
}

Access the class or interface in another namespace:

NameSpaceName.ClassName;

TypeScript Multi-file namespaces:

We can split the namespace into multiple files. As these multiple files will have dependencies we have to add reference tag to tell the compiler about the relationships between the files.

/// <reference path = "FileName.ts" />

Example:

Validation.ts

namespace Validation {
    export interface StringValidator {
        isValid (s: string): boolean;
    }
}

LettersValidator.ts

/// <reference path="Validation.ts" />
namespace Validation {
    const lettersRegexp = /^[A-Za-z]+$/;
    export class LettersOnlyValidator implements StringValidator {
        isValid (s: string) {
            return lettersRegexp.test(s);
        }
    }
}

ZipCodeValidator.ts

/// <reference path="Validation.ts" />
namespace Validation {
    const numberRegexp = /^[0-9]+$/;
    export class ZipCodeValidator implements StringValidator {
        isValid (s: string) {
            return s.length === 5 && numberRegexp.test(s);
        }
    }
}

Test.ts

/// <reference path="Validation.ts" />
/// <reference path="LettersValidator.ts" />
/// <reference path="ZipCodeValidator.ts" />
//Some samples to try
let strings = ["You", "53454", "Hello"];
 
// Validators to use
let validators: { [s: string]: Validation.StringValidator; } = {};
validators["ZIP code"] = new Validation.ZipCodeValidator();
validators["Letters only"] = new Validation.LettersOnlyValidator();
 
//Show whether each string passed each validator
for (let s of strings) {
    for (let name in validators) {
        console.log(`"${ s }" - ${ validators[name].isValid(s) ? "Valid" : "Invalid" } ${ name }`);
    }
}


Please follow and like us:
error








Copyright © 2019 CodesJava DMCA.com Protection Status