6

I am watching a video tutorial and I have created a a new typescript project. First I created in the root directory the following namespace (utilityFunctions.ts) :

namespace Utility {

    export namespace Fees {
        export function CalculateLateFee(daysLate: number): number {
            return daysLate * .25;
        }
    }

    export function MaxBooksAllowed(age: number): number {
        if (age < 12){
            return 3;
        }
        else {
            return 10;
        }
    }

    //function that is not exported
    //use it only inside the namespace
    function privateFunc(): void {
        console.log('This is private...');
    }

}

Then I created another typescript file (app.ts) to use the above namespace code :

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


let fee: number = Utility.Fees.CalculateLateFee(10);
console.log(`Fee: ${fee}`);

When I run the app.js file (using webstorm latest version) I am getting the following error :

/Users/Administrator/.nvm/versions/node/v6.5.0/bin/node /Users/Administrator/WebstormProjects/NamespaceDemo/app.js
/Users/Administrator/WebstormProjects/NamespaceDemo/app.js:5
var fee = Utility.Fees.CalculateLateFee(10);
                       ^

ReferenceError: Utility is not defined
    at Object.<anonymous> (/Users/Administrator/WebstormProjects/NamespaceDemo/app.js:5:24)
    at Module._compile (module.js:556:32)
    at Object.Module._extensions..js (module.js:565:10)
    at Module.load (module.js:473:32)
    at tryModuleLoad (module.js:432:12)
    at Function.Module._load (module.js:424:3)
    at Module.runMain (module.js:590:10)
    at run (bootstrap_node.js:394:7)
    at startup (bootstrap_node.js:149:9)
    at bootstrap_node.js:509:3

Process finished with exit code 1

My tsconfig.json file is the following :

{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es5",
        "noImplicitAny": false,
        "sourceMap": true
    },
    "exclude": [
        "node_modules"
    ]
}

And my tslint.json file is the following (although I don't think that the linter has anything to do with compilation errors):

{
    "extends": "tslint:recommended",

    "rules": {
        "comment-format": [false, "check-space"],
        "eofline": false,
        "triple-equals": [false, "allow-null-check"],
        "no-trailing-whitespace": false,
        "one-line": false,
        "no-empty": false,
        "typedef-whitespace": false,
        "whitespace": false,
        "radix": false,
        "no-consecutive-blank-lines": false,
        "no-console": false,
        "typedef": [true,
            "variable-declaration",
            "call-signature",
            "parameter",
            "property-declaration",
            "member-variable-declaration"
        ],
        "quotemark": false,
        "one-variable-per-declaration": false,
        "max-line-length": 160,
        "object-literal-sort-keys": false,
        "trailing-comma": false,
        "variable-name": [true,
            "ban-keywords",
            "check-format",
            "allow-leading-underscore"
        ]
    }

}
2
  • It might be helpful to see what your folder structure looks like. It may be that it just can't find the file. I haven't found anything definitive on how script tags are resolved, but you may need to add to your tsconfig this compiler option "moduleResolution": "node" I'm not sure, but that may affect script tag resolution as well. Commented Sep 13, 2016 at 14:26
  • 1
    Ok.Mystery solved!I just watched the rest of the video and the guy gets exactly the same error.It is a nodejs problem.NodeJS is not accepting namespaces in multiple files (it accepts only modules - at least that's what the tutor says) so I had to add the line "outFile": "out.js" to my tsconfig.json and then run this single file that gathers all project's typescript files into one single javascript file. Commented Sep 13, 2016 at 17:35

3 Answers 3

6

As your utilityFunctions.ts is already a module then there's no need to wrap what's inside of it in a namespace.

Also, using /// <reference ... is just for the compiler but node won't use it and so it doesn't know where to find utilityFunctions.
You need to import it.

Here are how the files should look:

export namespace Fees {
    export function CalculateLateFee(daysLate: number): number {
        return daysLate * .25;
    }
}

export function MaxBooksAllowed(age: number): number {
    if (age < 12){
        return 3;
    }
    else {
        return 10;
    }
}

//function that is not exported
//use it only inside the namespace
function privateFunc(): void {
    console.log('This is private...');
}

And:

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

import * as Utility from "./utilityFunctions"

let fee: number = Utility.Fees.CalculateLateFee(10);
console.log(`Fee: ${fee}`);

You can also completely remove the /// <reference as the compiler can find the .ts file when importing.

Sign up to request clarification or add additional context in comments.

2 Comments

This is working but I have not arrived yet at modules section in the tutorial (this is right after the current video) and I am also wondering how the author manage to use this namespace syntax (although he is using Visual Studio Code) and get his code running without errors.
Check my comment after my original post.
1

Quick And Easy in Visual Studio

Drag and Drop the file with .ts extension from solution window to editor, it will generate inline reference code like..

/// <reference path="../../components/someclass.ts"/>

Comments

0

Typescript transpiles to javascript, and since javascript is not a compiled language, you need to run or load all of your javascript files in order if one is dependent on the other.

Namespaces are basically global objects in javascript, so they need to be defined and loaded before they are used.

In a web page the loading is typically specified with script tags like such in the main html file.

<script src="utilityFunction.js"></script>
<script src="app.js"></script>

This will load the utilityFunction file first and define the object/namespace Utility so that when app.js runs it will have visibility of the object Utility

I'm not really sure how WebStorm works, but it's likely that you need to define somewhere in your project what files are loaded and in what order.

1 Comment

This solution is perfectly fine for a browser.You can find the answer to this problem inside a comment I've made below my original post.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.