Problem with moving functions from one file to another file via export and import

I currently have the following file structure:

---utilities
-----index.ts
-----tools.ts
allfunctions.ts

Within the tools.ts file, I have defined several functions that I export using export const. One of them is the helloWorld function:

export const helloWorld = () => console.log('Hello World');

In the utilities/index.ts file, I've imported the tools file and exported it like this:

import * as toolsFunction from './tools';

export { toolsFunction }

Now in my allfunctions.ts file, I am trying to use the helloWorld function in the following way:

import { taskFunctions as Utility } from './utilities/';

taskFunctions.helloWorld();

Before compiling the code, everything works fine. However, when I try to compile, I encounter the following error message:

TypeError: Cannot read property 'helloWorld' of undefined

I'm not sure what mistake I might be making here. Could you provide some insight?

Answer №1

When using typescript's import to bring in a module, the syntax is as follows:

import * as myModule from './superModule'
myModule.doStuff()

or

import {doStuff} from './superModule'
doStuff()

or

import {doStuff as superFunction} from './superModule'
superFunction()

In this case, the issue arises because taskFunctions is not defined, and you should instead call your helloWorld function using Utility. Try :

import { toolsFunctions as Utility } from './utilities/';

Utility.helloWorld();

For further details, refer to https://www.typescriptlang.org/docs/handbook/modules.html

Answer №2

The reason for the issue is that you are not correctly invoking the helloWorld() function. The function is exported as toolsFunction, but you are trying to import it as taskFunctions in your allfunctions.ts. Additionally, you need to call the function using the new alias Utility. Your code should be updated as follows:

tools.ts

export const helloWorld = () => console.log('Hello World');

index.ts

import * as toolsFunction from './tools';

export { toolsFunction }

allfunctions.ts

import {toolsFunction as Utility} from './utilities/'

export {Utility};

usage in app.component.ts

import { Component } from '@angular/core';
import {Utility} from './allfunctions'

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular 4';

  constructor(){
    Utility.helloWorld();
  }
}

For a working demonstration, visit: https://stackblitz.com/edit/angular4-zzhcu5

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using TypeScript with React's forwardRef

Here's my code where I have utilized React's forwardRef: interface PropsDummy {} const ProfileMenu = forwardRef<HTMLInputElement, PropsDummy>((props, ref) => { console.log(ref.current); } However, I'm encountering a TypeScript e ...

How come the inference mechanism selects the type from the last function in the intersection of functions?

type T = (() => 1) & (() => 2) extends () => infer R ? R : unknown What is the reason that T is not never (1 & 2)? Does the type always come from the last function, or can it come from one of them? ...

Steps for converting a tsx file into a js file in React

Currently, I am in the process of a React Project and have numerous tsx files that I aim to convert for utilization as JavaScript within my project. What would be the best approach to achieve this task? ...

The act of exporting an enum from a user-defined TypeScript path leads to the error message "Module not

I have set up a custom path as explained in this particular discussion. "baseUrl": ".", "paths": { "@library/*": [ "./src/myFolder/*" ], } Within this module, I am exporting an Enum. export enum EN ...

The error with removing the form field control in Angular 7 persists

I am currently in the process of designing a registration page that includes fields for confirming passwords and emails. Users are required to re-enter their password and email address. Below is the structure of the FormGroup: ngOnInit() { this.basicInfo ...

Unable to loop through the Array

let Users = [ { name: 'John', id: '1', jp: 'USA' }, { name: 'Jane', id: '2', jp: 'Japan' }, ]; export function DisplayUsers(usersList) { return ( <div> {usersList?.map((user ...

Modifying a group of Components in Angular using a Service

Managing a set of Components involves changing their properties using a Service. The Components have a minimal model and are meant to remain compact. They are being rendered with *ngFor. The Service possesses a large Object and should possess the abilit ...

What is the correct way to trigger an event specified as a string parameter in the emit() function?

My current goal is to pass the emit name as a string (for example, 'showComponent') from child to parent. I then want to trigger another emit in the emitAction(callbackName: string) function, and finally execute the showComponent() function. I&a ...

Can you explain the distinction, if one exists, between a field value and a property within the context of TypeScript and Angular?

For this example, I am exploring two scenarios of a service that exposes an observable named test$. One case utilizes a getter to access the observable, while the other makes it available as a public field. Do these approaches have any practical distincti ...

What purpose does the pipe method serve in RxJS?

It seems like I understand the basic concept, but there are a few unclear aspects. Here is my typical usage pattern with an Observable: observable.subscribe(x => { }) If I need to filter data, I can achieve this by: import { first, last, map, reduce, ...

Showcase pictures within an angular smart table

Is it possible to display images in a column within an ng smart table? We have several columns consisting mostly of data, with one column dedicated to displaying images. Following the ng smart table concept, I attempted to implement the code below which cu ...

Bringing in the RangeValue type from Ant Design package

Currently working on updating the DatePicker component in Ant Design to use date-fns instead of Moment.js based on the provided documentation, which appears to be functioning correctly. The suggested steps include: import dateFnsGenerateConfig from ' ...

Using Typescript to implement a conditional return type and ensuring that the value types are consistent together

I am working with a useSelectedToggle hook that helps in connecting the UI state to the open/closed status of a dialog where it will be displayed. The toggle defines the value as (T) when it is open, and null when it is closed. How can I enforce stricter ...

Incorporate a new method into a TypeScript class from a separate file

I'm curious about the feasibility of adding additional functions to a class prototype in Typescript. Here's my dilemma: I have a file containing a class, for example image.ts: export class Image { b64img: string; } Since this class is gene ...

Consolidate type definition within a tsx file using VS Code

Whenever I define a type in a TypeScript file (.ts) on VS Code, I notice that there is no option to collapse the definition. Here's an example: export type Test = { someValue: string, someOtherValue: string, yetAnotherValue: string }; I ...

Translate Firestore value updates into a TypeScript object

Here are the interfaces I'm working with: interface Item { data: string } interface Test { item: Item url: string } In Firestore, my data is stored in the following format: Collection Tests id: { item: { data: " ...

Disarrayed generic parameters in TypeScript

The title of the question may not be perfect, but it's the best I could do. Imagine a scenario where there is a function that accepts a callback along with an optional array. The callback takes an index and another optional array as parameters, and t ...

Is there documentation available for the gcloud output formats, such as the JSON output for each command?

As I work to script the gcloud tool in a TypeScript-aware JavaScript environment known as SLIME, I am utilizing the --format json feature for formatting. The integration is smooth, but I find myself manual analyzing the JSON output of each command to und ...

What is the functionality of input onChange in React when using state management?

Whenever I try to log the value of the input after each onChange event, there seems to be an odd one event delay. For example, if 'some text' is the default input value and I remove the letter 't' by pressing backspace/delete, it first ...

Configuring the tsconfig outDir will specify where the output files will be stored

What am I missing in the tsconfig settings if I only want to output files in the root directory? If I set it as "rootDir":"src" "outDir":"build", or "rootDir":"src" "outDir":"&q ...