Namespaces in Typescript

Namespaces in Typescript

Namespace is basically has collection of classes, interfaces, variables, functions together in one file.

Namespace Syntax:

namespace name{

export class {
}

export interface {
}

export const constname;

}

The code related in available under one namespace.

Namespace working example: testnamespace.ts

namespace StudentSetup {

    export interface StudDetails {
        name: string;
        age: number;
    }

    export function addSpace(str) { // will add space to the string given
        return str.split("").join(" ");
    }

    export class Student implements StudDetails {
        name: string;
        age: number;

        constructor(studentdetails: StudDetails) {
            this.name = studentdetails.name;
            this.age = studentdetails.age;
        }

        getName(): string {
            return this.name;
        }
    }
}

The name of the namespace is StudentSetup, you have added a interface StudDetails , function addSpace and a class called Student.

Accessing Namespace

Following is the code where you are using the namespace StudentSetup.

testStudentSetup.ts

let a = new StudentSetup.Student({ name: "Harry", age: 20 });

console.log("The name is :" + StudentSetup.addSpace(a.getName()));

The class, interface, a function available inside a namespace has to be referred using the name of the namespace example StudentSetup.addSpace to access the function, StudentSetup.Student to access the class.

You can compile both files into one js as shown below:

tsc --outFile namespace.js testnamespace.ts  testStudentSetup.ts

Check the output in command prompt using below command:

node namespace.js

It will display output as :

The name is: H a r r y

Ambient Declarations in Typescript

Typescript allows you to use third-party javascript files using ambient declaration. The advantage of this feature is that you don’t have to rewrite and yet use all the features of the library in typescript.

Ambient Syntax

To declare ambient module:

declare module moduleName {
   //code here
}  

The ambient file has to saved as :

filename.d.ts

To use the file filename.d.ts in your .ts you need to refer it as:

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

The ambient type declaration in typescript will have a reference to the third party library and will re-declare the functions required with its own type. For example, consider you have a small javascript library, as shown below:

Third Party JavaScript file: testString.js

Example: testString.js

var StringChecks = {
    isString: function (str) {
        return typeof str === "string";
    },

    convertToUpperCase: function (str) {
        return str.toUpperCase();
    },

    convertToLowerCase: function (str) {
        return str.toLowerCase();
    },

    convertToStringBold: function (str) {
        return str.bold();
    }
};

You have an object called StringChecks which has functions like isString, convertToUpperCase, convertToLowerCase, and converToStringBold.

Creating of Ambient Module in Typescript

Now will create an ambient module which will have reference to above js functions and also add type check as per our requirements.

Filename : tstring.d.ts

declare module TestString {

    export interface StringsFunc {
        isString(str: string): boolean;
        convertToUpperCase(str: string): string;
        convertToLowerCase(str: string): string;
        convertToStringBold(str: string): string;
    }
}

declare var StringChecks: TestString.StringsFunc;

You have to define a module name as TestString and have exported interface StringsFunc.

isString(str: string): boolean

=> This will take param as a string and the return type will be boolean. When using in your .ts file in case you happen to pass the param as a number or anything other than string it will give you a compile type error.

convertToUpperCase(str:string): string

=> This will take argument as string and return a string.Same goes for convertToLowerCase(str: string) : string; and convertToStringBold(str: string): string ;

Since in the javascript file you have the object name as StringChecks, finally we need to refer the same in the .d.ts file which is done as :

declare var StringChecks: TestString.StringsFunc;

Using Ambient module in Typescript

Now here is the test.ts file where will use ambient file tstring.d.ts

Example: test.ts

/// <reference path="tstring.d.ts"/>
let str1 = StringChecks.isString("Hello World");
console.log(str1);
let str2 = StringChecks.convertToUpperCase("hello world");
console.log(str2);
let str3 = StringChecks.convertToLowerCase("HELLO");
console.log(str3);
let str4 = StringChecks.convertToStringBold("Hello World");
console.log(str4);

Compile typescript tsc test.ts to test.js

/// <reference path="tstring.d.ts"/>
var str1 = StringChecks.isString("Hello World");
console.log(str1);
var str2 = StringChecks.convertToUpperCase("hello world");
console.log(str2);
var str3 = StringChecks.convertToLowerCase("HELLO");
console.log(str3);
var str4 = StringChecks.convertToStringBold("Hello World");
console.log(str4);

Now you can use test.js in html file and also the library file testString.js

<html>			
<head>			
    <title>Test Typescript Ambient</title>			
    <script src="/testStrings.js"></script>			
    <script src="/test.js"></script>			
</head>			
<body>			
</body>			
</html>

This is the output seen in the console:

true			
HELLO WORLD			
hello			
<b>Hello World</b>

About Author

Leave a Reply

Your email address will not be published. Required fields are marked *

PAGE TOP
error

Enjoy this blog? Please spread the word :)

RSS
Follow by Email