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

When the down arrow key is pressed, the focus of the radio button is lost

I've been facing a persistent accessibility issue with the main-component in Angular. This component contains four different templates, but depending on the radio button selection, other templates are displayed. The problem arises when these templates ...

"Upon submitting a form in React JS, the components will automatically trigger a

Within my application, there is a Mobx storage in conjunction with a modal window component. The form within the modal window allows me to collect all the properties and push them into an array named 'cart' within the storage as an object. Take a ...

Typescript error in RxJS: Incorrect argument type used

I came across this code snippet from an example in rxjs: Observable.fromEvent(this.getNativeElement(this.right), 'click') .map(event => 10) .startWith({x: 400, y: 400}) .scan((acc, curr) => Object.assign({}, acc, {x: acc ...

Accessing properties for objects with map-like characteristics

Many interfaces allow for arbitrary data, as shown below: interface Something { name: string; data: { [key: string]: any }; } The problem arises when trying to access or set values on objects with arbitrary keys in Typescript. let a: Something = { ...

Establishing the placement of map markers in Angular

Currently, I am in the process of developing a simple web application. The main functionality involves retrieving latitude and longitude data from my MongoDB database and displaying markers on a map, which is functioning correctly. However, the issue I&apo ...

What is the correct way to invoke a static TypeScript class function in JavaScript?

Recently, I encountered a scenario where I have a TypeScript script called test.ts structured like this: class Foo { public static bar() { console.log("test"); } } The requirement was to call this TypeScript function from plain JavaScript ...

"Encountering difficulties while setting up an Angular project

I am currently working on setting up an Angular project from scratch. Here are the steps I have taken so far: First, I installed Node.js Then, I proceeded to install Angular CLI using the command: npm install -g @angular/cli@latest The versions of the ...

Guide to implement editable columns in Angular 4 with a click functionality

I have a table displaying records using ngFor, and I am looking to enable editing of a column upon clicking it. <tr *ngFor="let cd of descriptionCodes; let i = index"> <td><input type="checkbox"></td> <td> {{cd.code}} ...

What is the methodology for obtaining the setter property type in TypeScript?

Describe a scenario where an object contains both getter and setter methods with different types. How can we determine the type of the setter function? Consider defining an object with getter and setter functions like the example below: type Foo = { g ...

Combine two arrays into one

When attempting to combine two arrays, the result looks like the image linked below: I want the merged array to resemble the following example: {0: {…}, storedArr: Array(2)} 0: address: "ifanio de los Santos Ave, Mandaluyong, 1550 Metro Manila, Phi ...

Troubleshooting the lack of success in enhancing global scope within Typescript

Currently, I am working on a microservices application where I have two very similar services that use practically the same packages. To perform some testing, I decided to add a function to the global scope and modified it slightly to prevent any TypeScrip ...

Confirming changes to checkbox values in Angular 2 prior to updating

My current challenge involves implementing a confirmation dialog in my application, and I'm feeling a bit unsure about the logic behind it. UserDetailsComponent.ts import { Component, OnInit, OnDestroy, ViewChild, Input, OnChanges, SimpleChange } f ...

Incorporating interactive buttons within Leaflet popups

I'm facing an issue with adding buttons to a Leaflet popup that appears when clicking on the map. My goal is to have the popup display 2 buttons: Start from Here Go to this Location The desired outcome looks like this sketch: ___________________ ...

Error: The version of @ionic-native/[email protected] is not compatible with its sibling packages' peerDependencies

When attempting ionic cordova build android --prod, the following error occurred: I have tried this multiple times. rm -rf node_modules/ rm -rf platforms/ rm -rf plugins/ I deleted package.lock.json and ran npm i, but no luck so far. Any ideas? Er ...

Error in Jest Testing: An unexpected character '@' was encountered

Encountering issues with NuxtJS Jest tests and attempting to build a Nuxt app to test URL's due to route name errors in some components. Here is the code snippet I tried: beforeAll(async () => { nuxt = new Nuxt({ ...config, server: { port: 3001 } ...

Choose to either push as a single object or as individual items

I have a quick question that I'd like to get some clarity on. Can someone explain the distinction between these two code snippets: export const addToCart = function(product, quantity){ cart.push({product, quantity}); console.log(`${quantity} ...

"Can you share a method to extract the value from a TextField component in a React hook-based Material-

Currently, I am using Material-UI within a React project and have a component set up like this: const UserDetail = (props: ListDetailProps) => { const oldpassword = useRef<TextFieldProps>(null); const newpassword = useRef<TextFieldProps ...

What steps should I take to resolve the error message "ESLint encountered an issue determining the plugin '@typescript-eslint' uniquely"?

Struggling to enable eslint linting in an ASP.NET Core MVC project that incorporates React.js and typescript? I'm facing a tough challenge trying to resolve the error mentioned above. In my setup, I'm using Visual Studio 2022 Community Edition 1 ...

Try using ngFor within the insertAdjacentHTML method

When a user clicks, I dynamically attach an element inside a template like this: this.optionValue = []; youClickMe(){ var moreput = ''; moreput += '<select">'; moreput += '<option *ngFor="let lup of opti ...

Having trouble getting the styles property to work in the component metadata in Angular 2?

Exploring Angular 2 and working on a demo app where I'm trying to apply the styles property within the component metadata to customize all labels in contact.component.html. I attempted to implement styles: ['label { font-weight: bold;color:red } ...