Tips for passing either two parameters or none into a function in TypeScript?

My goal was to enhance a function that simply returns a status. It originally only accepted a logger and a message as parameters for logging purposes.

export function status(logger: Logger, reason: string) {
  logger.info(reason);
  return {
    result: 'ok'
  };
}

However, I wanted to make these parameters optional so that if no logging is needed, they do not have to be passed. This led me to modify the function like this:

export function status(logger?: Logger, reason?: string) {
  reason && logger?.info(reason);
  return {
    result: 'ok'
  };
}

Yet, I found that it was still possible to provide a logger without providing a reason, which was not what I intended. My aim was for the function to either accept both parameters or none at all. So, I attempted the following approach:

export function status(param: {logger: Logger, reason: string} | {} = {}) {
  param?.logger.info(reason);
  return {
    result: 'ok'
  };
}

Unfortunately, I encountered an error stating

TS2339: Property 'logger' does not exist on type '{} | { logger: Logger; reason: string; }'.   Property 'logger' does not exist on type '{}'.
and I am unsure how to resolve this issue. Could you kindly explain how I could achieve my desired functionality?

Answer №1

UPDATE: The structure of the Logger type was not provided in your initial question. Based on the code you shared, it seems that the Logger type may resemble the following:

type Logger = { info: (someInfo: string) => void }

Determine the type of parameters that the status function will receive:

type paramsStatus = {
  logger: { info: (someInfo: string) => void },
  reason: string,
}

The use of the ? operator makes the params optional. However, since logger and reason are mandatory fields based on the defined type, both must be included when calling the status function. It is acceptable to include both or neither.

export function status(params?: paramsStatus) {
  params && params.logger.info(params.reason); //If params exist, then log the information
  return {
    result: 'ok',
  };
}

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

Jest: A guide on mocking esModule methods

In my code, I have a function that utilizes the library jszip to zip folders and files: // app.ts const runJszip = async (): Promise<void> => { const zip = new Jszip(); zip.folder('folder')?.file('file.txt', 'just som ...

Adapting the current codebase to be compatible with Typescript

Currently, my codebase is built with redux, redux-saga, and react using plain Javascript. We are now considering incorporating Typescript into the project. Some questions arise: Can plain Javascript files coexist with tsx code? I believe it's possibl ...

Get the shared elements from several arrays with JavaScript

Find the shared value of 12 from the given array For example: If the input is as follows: [ [12, 6],[12, 11, 9, 8, 1],[12, 11, 9, 8, 6, 1],[12, 11, 9, 8, 6, 1],[12, 11, 9, 8, 6, 1] ] The expected Output should be : [12] ...

What is the best way to bring a JavaScript library into a TypeScript project if the library includes a declaration file?

I have been attempting to utilize the type definitions from the callbag library. Unlike other libraries, callbag declares its type definition file within its package.json and is not included in DefinitelyTyped. However, when I try to import the library, I ...

Dealing with nullable objects in Typescript: Best practices

Looking for a solution to have a function return an object or null. This is how I am currently addressing it: export interface MyObject { id: string } function test(id) : MyObject | null { if (!id) { return null; } return { ...

Steps for setting up a Subscription instanceWould you like me to

I am currently utilizing a Subscription in Angular to extract a parameter from the route. Below is the code snippet: import { Component, OnInit, OnDestroy } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import ...

What are the best practices for securely storing SSL certificates and public/private keys?

I possess keys that appear like this. MIID0DCCArigAwIBAgIBATANBgkqhkiG9w0BAQUFADB/MQswCQYDVQQGEwJGUjET MBEGA1UECAwKU29tZS1TdGF0ZTEOMAwGA1UEBwwFUGFyaXMxDTALBgNVBAoMBERp bWkxDTALBgNVBAsMBE5TQlUxEDAOBgNVBAMMB0RpbWkgQ0ExGzAZBgkqhkiG9w0B CQEWDGRpbWlAZGltaS5mcjA ...

Create a new FetchEvent instance within Jest specifically for a Cloudflare Worker deployment

The TypeScript template repository for Cloudflare Workers includes a test that mocks a GET request by instantiating the Request to simulate the input parameters for the handleRequest function. After some modifications to the template, I now pass the raw F ...

Frequent occurrence when a variable is utilized prior to being assigned

I am currently working with a module import pino, { Logger } from 'pino'; let logger: Logger; if (process.env.NODE_ENV === 'production') { const dest = pino.extreme(); logger = pino(dest); } if (process.env.NODE_ENV === &apo ...

React with Typescript: It appears that you are attempting to utilize Typescript without having it properly installed on your system

I am embarking on creating a React application integrated with TypeScript. Initially, I visited the React website to seek guidance on incorporating TypeScript in my project. The website directed me to execute the following command in the terminal: npx crea ...

Is there a way to retrieve the groups of match/matchAll similar to accessing an array?

My goal is to convert a version string to a number using the following code: function convertVersionToNumber(line) { const groups = line.matchAll(/^# ([0-9]).([0-9][0-9]).([0-9][0-9])\s*/g); return parseInt(groups[1] + groups[2] + groups[3]) ...

Middleware in Express.js that allows a function to be executed every time `res.send()` is called

As of now, I am creating APIs using express.js and I aim to send a standard response format like so : res.send({status : 'suceess' , msg : '' , data : [] }); Across all the controllers (functions managing my routes) My attempted sol ...

Tips for managing numerous HTTP requests in Angular 6

I have a method that is trying to chain together 3 requests like this: showProfileDetails() { this.getUserInfo(this.currentUser.id).pipe( mergeMap(e => this.getAccounts(this.currentUser.id) ), mergeMap(e => this.getPayments ...

The variable is currently undefined because it has an array assigned to it

Upon selecting multiple checkboxes for variants, I am retrieving checked data using the following method: get selectedIdsFromViolCategoriesFormArray(): string[] { return this.violCategories .filter((cat, catIdx) => this.violCategoriesFormArr. ...

Exploring the traversal of an array of objects within Tree Node

How can I transform my data into a specific Tree Node format? Is there a method (using Typescript or jQuery) to iterate through each object and its nested children, grandchildren, and so on, and modify the structure? Current data format { "content" ...

Are you harnessing the power of Ant Design's carousel next and previous pane methods with Typescript?

Currently, I have integrated Ant Design into my application as the design framework. One of the components it offers is the Carousel, which provides two methods for switching panes within the carousel. If you are interested in utilizing this feature using ...

Invoke a public method in TypeScript

I'm a newcomer to typescript. In my node-express application, I am trying to call a public function. However, I keep encountering an issue where this is always undefined, leading to errors whenever I attempt to call the public function. Below is the s ...

Definition file in TypeScript for an npm package provided by an external source - constructor

In my Node project, I am utilizing ES6 and Typescript. Despite this, there is a commonjs library that I need to incorporate. To address this, I have created my own .d.ts declaration file for the library: module "@alpacahq/alpaca-trade-api" { e ...

What is causing Angular 6 to fail in sending HTTP Get/Post requests?

In Angular 6, I have created a LoginService like this: @Injectable() export class LoginService { constructor(private http: HttpClient) { } login(): Observable<boolean> { var url = `${environment.baseAPIUrl}${environment.loginUrl}`; ...

Nexus and GraphQL: The root typing path for the "context" type is not found

I’m currently working on integrating GraphQL into Next.js API routes. For writing the GraphQL schema, I’m utilizing Nexus. Here are the two essential files: context.ts and schema.ts, that help in setting up Nexus development mode. // context.ts import ...