TypeScript module

module

Don’t want to write long long source codes in one file.
Want to separate module each file.

TypeScript has module idea.
Add export keyword at the beginning of word.

Example

export interface Validator {
    isOK(s: string): boolean;
}

interface has export keyword
We can use this out of this file

import {Validator} from "./Validation";

export class LengthValidator implements Validator {
    isAcceptable(s: string) {
        return s.length > 10;
    }
}

import “modulename(export)” from “source code path/name”

Change name in

import { CodeValidator as CV } from "./CodeValidator";

let cv = new CV();

jQuery, 3rd party javascript library

We want to use javascript library in TypeScript.
TypeScript prepares.
Definition file(.d.ts). This is for typescript and javascript variable conversion definition file.
Some people prepare that kind of file.
You can download from Github.
DefinitionTyped prepares a bunch of ts files.

Example for jQuery

I tried jQuery version 3.0

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>jQuery</title>
    <script src="../node_modules/jquery/dist/jquery.js"></script>
</head>
<body>
    <script src="jquerymain.js"></script>
</body>
</html>

jquerymain.ts

/// <reference path="jquery.d.ts" />
$("body").html("Hello jQuery");

The key point is reference comment. This means that it includes jquery.d.ts in this file.

Browser, Node

Browser JavaScript and Node JavaScript is a bit different. require doesn’t work in browser version.
Gulp has browserify to optimize that kind of difference.
If you want to know browserify, please read my other entry (TypeScript and Gulp)

namespace

Like Java, C#, we can use namespace

namespace People {
    export interface Person {
        say(message: string);
    }

    const t = 113;

    export class Student implements Person {
        say(message: string) {
            console.log(message);
        }
    }
}

let student = new People.Student();