2

I am pretty new to typescript, but now I have a problem. I've written a function in Typescript out of every class

function someFunction(){
}

And now I wanted to call the function from another TS file and i declared it as follows:

declare function someFunction(): void;

But this won't work in the browser console I get the error

Uncaught ReferenceError: someFunction() is not defined

File one looks like:

export class SomeClass{
}

export function someFunction(){
}

File two :

///<reference path="File1.ts" />
export class SomeOtherClass{
 someFunction();
}
2
  • Added example above :) Commented Dec 15, 2016 at 13:36
  • In this function is an algorithm which I wanna call from another class too. (Controller) So that I dont have to duplicate the code Commented Dec 15, 2016 at 13:42

2 Answers 2

5

You do not need to declare the function, you can reference the file that has it and then the compiler will know it.
For example:

// file1.ts

function someFunction(): string {
    ...
}

Use it:

// file2.ts

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

let mystr = someFunction();

The error you are getting is a runtime error because you don't include file1.js:

<script src="file1.js" />

Edit

The code you added to your question compiles for me with two changes:

(1) removed exports:

// file1.ts

class SomeClass {}

function someFunction() {}

(2) added a class method:

// file2.ts

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

class SomeOtherClass {
    fn() {
        someFunction();
    }
}

Edit by Original Poster: Second Solution (worked for me)

// file1.ts

export function someFunction(){
    ...
}

Use it:

// file2.ts

import myFunc = require('./file1');

myFunc.someFunction();
Sign up to request clarification or add additional context in comments.

13 Comments

The compiler doesn't recognize this function when I set a reference to the file...
Right, add export. I fixed my answer.
In file1.ts I added what you said export function etc. but It still won't load, i get a compiler error again
I checked it myself, and it works without the export that I've added (now removed). For me it works and I get no compilation errors. What are you getting?
I think I should say I work with VS Code and Gulp. The built in INtelliSense says "Cannot find name someFunction" #update start post edit
|
-1

I don't get exactly what you are trying to do, but in typescript defining a function is done like this:

public someFunction(): void {}

You can replace public with private or protected according to what you need, or even remove it

Calling from the browser should be done by the framework you use using events (click) etc

1 Comment

No, that's not a class method, it's a function outside of a class.

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.