Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I declare a function from another file in Typescript?

People also ask

Can we export function in TypeScript?

YES, TypeScript can export a function! "Any declaration (such as a variable, function, class, type alias, or interface) can be exported by adding the export keyword."

What is D TS in TypeScript?

The "d. ts" file is used to provide typescript type information about an API that's written in JavaScript. The idea is that you're using something like jQuery or underscore, an existing javascript library. You want to consume those from your typescript code.

How do I import something into TypeScript?

Use import myFunction from "./myModule" to bring it in. More commonly, TypeScript modules say export myFunction in which case myFunction will be one of the properties on the exported object. Use import { myFunction } from "./myModule" to bring it in.


You can do this (assuming title and message are both supposed to be strings):

interface alertWinInterface{
    (title:string, message: string):any;
}

declare var alertWin: alertWinInterface;

You could put this in the same file, or put it in a separate ambient definitions file (.d.ts) which you import:

/// <reference path="myDefinitions.d.ts" />

Or, you could just import the other file that has the actual function definition, but you won't get static typing support.


This approach seems to work for me:

declare function alertWin(title: string, message: string) : void;

And as with Matt's solution you put it in a definition file and then reference it.


You just need to tell the tools and compiler where to find your function, by adding a reference to the top of your file:

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

Additionally, all of your parameters are currently typed as any, you can type them explicitly if you wish.

function alertWin(title: string, message: string) : void {
   //.......
   //.......
}