Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a function from another file in typescript?

Tags:

typescript

This question might be dum. I am a beginner for typescript. In file A, I want to call a function defined in file B. How do I do this?

like image 420
孔子胤 Avatar asked Mar 13 '18 04:03

孔子胤


People also ask

What does import do in TypeScript?

TypeScript also shares the same concept of a module. Any file which contains a top-level import or export is considered a module. The module is designed to arrange a code written in TypeScript and used as a local scope. Modules are basically scripts written in separate files.

How do I import export classes in TypeScript?

The export = syntax specifies a single object that is exported from the module. This can be a class, interface, namespace, function, or enum. When exporting a module using export = , TypeScript-specific import module = require("module") must be used to import the module.

Can I import a TypeScript into JavaScript?

Importing TypeScript files dynamically into JavaScript requires additional compilation step, which is troublesome to write for many. Popular typescript-require package seems to be obsolete and doesn't allow much customization.


2 Answers

You need to export the function in the file:

// File B
export function exampleFunction() {}

You can then import it in the other file for use:

// File A
import { exampleFunction } from 'path/to/fileb';
like image 120
Daniel W Strimpel Avatar answered Oct 04 '22 14:10

Daniel W Strimpel


Use the appropriate import and export statements.

Given the following file layout:

├── a.ts
└── b.ts

a.ts

import {myFn} from 'b';

myFn();

b.ts

export function myFn() {
    /* ... */
}
like image 34
Robby Cornelissen Avatar answered Oct 04 '22 14:10

Robby Cornelissen