TypeScript namespaces

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;

Example:

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

    const lettersRegexp = /^[A-Za-z]+$/;
    const numberRegexp = /^[0-9]+$/;

    export class LettersOnlyValidator implements StringValidator {
        isValid(s: string) {
            return lettersRegexp.test(s);
        }
    }

    export class ZipCodeValidator implements StringValidator {
        isValid(s: string) {
            return s.length === 5 && numberRegexp.test(s);
        }
    }
}

//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 }`);
    }
}

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.

/// 

Example:

Validation.ts

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

LettersValidator.ts

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

ZipCodeValidator.ts

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

Test.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:
Content Protection by DMCA.com