Reputation: 1718
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();
}
Upvotes: 2
Views: 11981
Reputation: 164139
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" />
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();
Upvotes: 5
Reputation: 2548
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
Upvotes: -1