transferring libraries via functions in TypeScript

As I work on developing my app, I have decided to implement the dependency-injection pattern. In passing mongoose and config libraries as parameters, I encountered an issue with the config library. Specifically, when hovering over config.get('dbUri'), an error message pops up saying: 'Untyped function calls may not accept type arguments.ts(2347)'

app.ts

(async () => await initializeDatabaseConnection(mongoose, config))();

connect.ts

async function initializeDatabaseConnection(mongoose: any, config: any):Promise<void>{
    try {
        const dbUri = config.get<string>('dbUri');
        
        await mongoose.connect(dbUri, () => {
            console.log('connected to the database successfully!');
        });
    } catch (error) {
        process.exit(1)
    }
}

export default initializeDatabaseConnection;

Answer №1

You have entered the value config as any, and then attempted to use it as if it were a generic parameter. However, since any signifies that TypeScript does not know the type of this variable, you cannot treat it as having a generic parameter.

To quickly resolve this issue, eliminate the <string>:

const dbUri = config.get('dbUri');

Nevertheless, a strongly-typed solution would be more appropriate in this scenario.

The type for mongoose is likely the type imported from import mongoose from 'mongoose'. It appears you will need to obtain the typeof mongoose since the package may not export a specific type for this purpose.

Subsequently, you must type config based on its actual type. Assuming your config resembles something like:

class ConfigService {
  get<T>(prop: string): T {
    return someConfigObject[prop]
  }
}

And at some point during dependency injection, you instantiate an object of that class.

Following these steps, you can specify the type for connectDb as shown below:

import type mongooseGlobal from 'mongoose'

async function connectDb(
  mongoose: typeof mongooseGlobal,
  config: ConfigService
): Promise<void>{
  //...
}

The key takeaway here is that you must determine the type of the object you wish to pass as a parameter to a function. If an appropriate type already exists, utilize it. If not, utilize typeof to derive the type from a given value.

Playground

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

Is there a way to ensure an ajax call finishes executing without relying on 'async: false' or callbacks?

In my view, I have implemented a TypeScript code defining a KnockoutJS binding handler for a clickable element as shown below: module MyModule { export interface ICopyButtonParams { dataUrl: string; } ko.bindingHandlers.copyButton = { ...

What is the best way to create an optional object parameter in Typescript?

I'm working on a function that looks like this: const func = (arg1: string, { objArg = true }:{ objArg: string }) => { // some code } Is it possible to make the second parameter (an object) optional? ...

Dealing with 'TypeError X is Not a Function' Error in Angular (TypeScript): Occurrences in Certain Scenarios and Absence in Others

Recently, I came across an odd issue in Angular 14 where a type error kept popping up. Although I managed to refactor the code and find a workaround, I'm quite intrigued as to why this issue is happening so that I can prevent it from occurring again i ...

Using WebdriverIO with Angular to create end-to-end tests in TypeScript that involve importing classes leads to an error stating "Cannot use import statement outside a module."

I am facing an issue while trying to set up a suite of end-to-end tests using wdio. Some of the tests utilize utility classes written in TypeScript. During the compilation of the test, I encountered the following error: Spec file(s): D:\TEMP\xx& ...

Error with tsc rootDir due to Docker's installation of yarn in root directory

I am encountering a problem with my node project which serves a simple "hello world" server. Everything runs smoothly when I run it locally, but when I try to run it inside Docker, a /opt/yarn-v1.21.1 folder is created which leads to a rootDir error: erro ...

How to utilize a parameter value as the name of an array in Jquery

I am encountering an issue with the following lines of code: $(document).ready(function () { getJsonDataToSelect("ajax/json/assi.hotel.json", '#assi_hotel', 'hotelName'); }); function getJsonDataToSelect(url, id, key){ ...

Firebase Promise not running as expected

Here is a method that I am having trouble with: async signinUser(email: string, password: string) { return firebase.auth().signInWithEmailAndPassword(email, password) .then( response => { console.log(response); ...

Having trouble locating the name WebGLObject in my TypeScript code

Every time I try to run ng serve command An error pops up on my screen saying: "WebGLObject cannot be found." ...

Create categories for static array to enable automatic suggestions

I have a JavaScript library that needs to export various constants for users who are working with vscode or TypeScript. The goal is to enable auto-complete functionality for specific constant options. So far, I've attempted to export a Constant in th ...

Are there any alternatives to ui-ace specifically designed for Angular 2?

I am currently working on an Angular2 project and I'm looking to display my JSON data in an editor. Previously, while working with AngularJS, I was able to achieve this using ui-ace. Here is an example of how I did it: <textarea ui-ace="{ us ...

Utilizing a variable name as an object key in TypeScript

Can this be achieved? static readonly statusMapping: { [key in UploadStatus]: PopupMessageStatus } = { UploadStatus.COMPLETED : PopupMessageStatus.COMPLETED } UploadStatus is an enum with numeric values, where UploadStatus.COMPLETED = 0 p ...

Reattempting a Promise in Typescript when encountering an error

I am currently working on a nodeJS application that utilizes the mssql driver to communicate with my SQL database. My goal is to have a unified function for retrieving a value from the database. However, in the scenario where the table does not exist upon ...

Converting an Array of Objects into a single Object in React: A Tutorial

AccessData fetching information from the database using graphql { id: '', name: '', regions: [ { id: '', name: '', districts: [ { id: '', ...

create a fresh variable instead of appending it to the current object

I'm encountering an issue where a new array is supposed to be added on callback using props, but instead an empty variable is being added. Here's the code snippet: const [data, setData] = useState({ title: "", serviceId: "", serviceNa ...

How can I limit generic types to only be a specific subtype of another generic type?

Looking to create a data type that represents changes in an object. For instance: const test: SomeType = { a: 1, b: "foo" }; const changing1: Changing<SomeType> = { obj: test, was: { a: test.a }, now: { a: 3 ...

Struggling with setting up a search bar for infinite scrolling content

After dedicating a significant amount of time to solving the puzzle of integrating infinite scroll with a search bar in Angular, I encountered an issue. I am currently using Angular 9 and ngx-infinite-scroll for achieving infinity scrolling functionality. ...

Error encountered with next-auth and the getServerSession function

Whenever I try to use the getServerSesssion function with all the necessary parameters, it results in a type error. In my code, I have the getServerAuthSession function defined as shown below: import { authOptions } from '@/pages/api/auth/[...nextauth ...

How to Hide Parent Items in Angular 2 Using *ngFor

I am dealing with a data structure where each parent has multiple child items. I am trying to hide duplicate parent items, but accidentally ended up hiding all duplicated records instead. I followed a tutorial, but now I need help fixing this issue. I only ...

Navigating to an external link directing to an Angular 5 application will automatically land on

I am struggling to comprehend why a link from an external source to my Angular app keeps redirecting to the default route page when accessed from a browser. The scenario involves a user entering an email address, triggering an API that sends an email cont ...

Error: Unable to use import statement outside of a module when deploying Firebase with TypeScript

Every time I try to run firebase deploy, an error pops up while parsing my function triggers. It specifically points to this line of code: import * as functions from 'firebase-functions'; at the beginning of my file. This is a new problem for me ...