Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript class per file in same namespace in Node.js

What is the pattern for one class per file where multiple classes (and therefore multiple files) contribute to the same namespace? I'm asking this specifically in a Node.js context.

I know how to define one class per file in the same namespace:

foo/A.ts:

module foo {
    export class A {
    }
}

foo/B.ts:

module foo {
    export class B {
    }
}

main.ts:

/// <reference path="./foo/A.ts"/>
/// <reference path="./foo/B.ts"/>

// TODO: How do I import the foo namespace at runtime?

TypeScript is supposedly a language for application-scale JavaScript development, yet we seem to be left out in the cold on the most fundamental aspect of application-scale development, which is how to layout and structure code files and how everything is linked together at runtime.

like image 454
Steve Avatar asked Jan 27 '14 05:01

Steve


People also ask

How do I refer a namespace in a file student ts?

To use it, it must be included using triple slash reference syntax e.g. ///<reference path="path to namespace file" /> . Must import it first in order to use it elsewhere. Compile using the --outFile command. Compile using the --module command.

Should you use namespace in TypeScript?

Typescript is a superset of ES6 so you have more power in what you can do, but that doesn't mean you should do it. In this case, ES6 solved the problem of modularization for us by doing a good job, so we don't need any namespace at all in common programs (unless you specifically want to use namespaces).

How do you identify a TS file as a module?

In TypeScript, files containing a top-level export or import are considered modules.

What are namespace exports?

Specifies which commands are exported from a namespace. The exported commands are those that can be later imported into another namespace using a namespace import command. Both commands defined in a namespace and commands the namespace has previously imported can be exported by a namespace.


1 Answers

As basarat mentions, in Node.js, files are modules. The correct way to write the code you are working on is:

foo/A.ts:

class A {
}

export = A;

foo/B.ts:

class B {
}

export = B;

main.ts:

import A = require('./foo/A');
import B = require('./foo/B');

This is detailed in the Imports and Exports section of The Definitive Guide to TypeScript.

like image 138
C Snover Avatar answered Oct 15 '22 09:10

C Snover