Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript - module functions reference in different file - "could not find symbol"

Apologies if the answer to this is simple, or I've mis-read the typescript documentation, but..

I have a module:

module Utils{

    export function MyFunction(str: string):string {
        return // something to do with string
    }

}

I want to use this in another .ts file (Clients.ts) so at the top I add a reference and try to use it:

/// <reference path="Utils.ts" />
Utils.MyFunction(str);

But get the following error:

/*

Compile Error. 
See error list for details
 [path]/Clients.ts(26,39): error TS2095: Could not find symbol 'Utils'.
 [path]/Clients.ts(30,49): error TS2095: Could not find symbol 'Utils'.
error TS5037: Cannot compile external modules unless the '--module' flag is provided.


*/

Could anybody explain what I'm doing wrong?

Using VS2012, with Web Essentials and TypeScript 0.9.1

Thanks.

like image 771
LiverpoolsNumber9 Avatar asked Mar 23 '23 14:03

LiverpoolsNumber9


2 Answers

Found the answer myself. What I was actually looking for was a static method on a class. As per the below:

class Utils {

    static MyFunction(str: string): string {
        return //... do something with string
    }
}

And this worked in the Client.ts

/// <reference path="Utils.ts" />
var x = Utils.MyFunction(str);
like image 67
LiverpoolsNumber9 Avatar answered Mar 25 '23 02:03

LiverpoolsNumber9


The error you are getting error TS5037: Cannot compile external modules unless the '--module' flag is provided. is not something you would get with your code.

You would get this only if you export something at the root level of your file. e.g.

export module Utils{ // Notice the export keyword 

    export function MyFunction(str: string):string {
        return // something to do with string
    }

}

In this case you are using an external module loader and typescript needs to know if its amd(requirejs/browser) or commonjs(node/server side)

PS: I did a video on the subject : http://www.youtube.com/watch?v=KDrWLMUY0R0&hd=1

like image 25
basarat Avatar answered Mar 25 '23 03:03

basarat