-1

Lets say I have this foo.js file where I declared a variable, a function and a class.

It is not in the project yet.

Now assume I want to use this variable, class and function in my home.ts method, or just make it globally available (to use in a home.ts method).

How can I make it happen?

Victor Ferreira
  • 6,151
  • 13
  • 64
  • 120

2 Answers2

0

lets say in your foo.ts file we have a funtion

myfunt(){
//your logic goes here
}

now if you want to make use of this function in home.ts file the

step1: import your foo.ts file in home.ts

step2: in your export class should look like this

    export class home extends foo { 
//since you have used extends keyword now you unlocked all the data in foo.ts file for home.ts file


        //here now try to access your myfunt() funtion


        constructor(){

           super.myfunt(); //user super keyword to access all the data available in foo.ts file
        }

    }
Mohan Gopi
  • 7,606
  • 17
  • 66
  • 117
0

You can use definition files (.d.ts).

First, check if foo.js have already a definition file created by the community. Check it here: http://microsoft.github.io/TypeSearch/ or here https://github.com/DefinitelyTyped/DefinitelyTyped

If it exists you can install it like this:

npm install --save @types/foo

If not, you can create your own definition file for this javascript file.

Let call it foo.d.ts with a content like this:

declare var data:any;
declare function myFunc(n:string);

Once you have it you can use it like a normal ".ts" file.

import * as foo from "./foo"; //"./foo" is the path of your .d.ts.
foo.myFunc()

More information here: https://blogs.msdn.microsoft.com/typescript/2016/06/15/the-future-of-declaration-files/

jordins
  • 390
  • 1
  • 5
  • 12
  • hey, thanks! where do I place foo.d.ts? when I 'import * from' `foo` I'm now importing from the foo.d.ts file? i'm gonna give it a try – Victor Ferreira Dec 11 '16 at 17:10
  • You can place foo.d.ts wherever you want, let's say next to your foo.js file. If you have created your own .d.ts, import it with the path where you have placed it like this ```import * as foo from "./foo" ```; If you have installed via npm you can import it like ```import * as foo from "foo"; ```. – jordins Dec 11 '16 at 17:19
  • I Wrote a declare statement in foo.d.ts and it said " 'foo.d.ts' is not a module.", then I did "export declare var..." and it passed. But when I tried to read something that should be in it (because it was in Foo in the foo.js file) it says "Property 'SomeProp' does not exist on type ..." – Victor Ferreira Dec 12 '16 at 01:46