17

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?

3 Answers 3

25

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() {
    /* ... */
}
Sign up to request clarification or add additional context in comments.

2 Comments

... as an extension to the question, based on a configuration file e.g. targetFn='myFn', how would you call targenFn() and have it invoke the named code?
15

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';

Comments

0

First you need to export the function:

a.ts:

function sum() {}

export sum

Now you just need to import that:

b.ts

import { sum } from "path to file"

Comments

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.