What is the best way to mandate a series of optional parameters when only one of them is specified as an argument?

I have a function that includes optional parameters:

export const sentryException = (
  error: Error,
  contextLabel?: string,
  contextInfo?: Context,
  specificTags?: SentryTags,
) => {

The last three parameters are optional. However, if contextLabel is provided, then contextInfo must also be provided. I would like to avoid having to do the following check:

if ((contextLabel && !contextInfo) || (contextInfo && !contextLabel)) {
   // throw error
}

Managing multiple required combinations of inputs can become cumbersome!

Is there a way to enforce that a subset of optional parameters must be passed in when a specific parameter is provided?


Edit: I want to clarify that the // throw error comment does not refer to the error parameter. It means that both contextLabel and contextInfo must always be defined (not undefined) for the function to execute.

For simplicity, let's say all types are strings except for error. Valid function calls could look like:

sentryException(err, 'a', 'b')
sentryException(err, 'a', 'b', 'c')
sentryException(err, undefined, undefined, 'c')
sentryException(err)

Answer №1

Perhaps utilizing a straightforward approach with function overloads is the way to go, creating customized argument type combinations:

function sentryException(
  contextLabel?: undefined,
  contextInfo?: undefined,
  specificTags?: string,
): void

function sentryException(
  contextLabel: string,
  contextInfo: string,
  specificTags?: string,
): void

function sentryException(
  contextLabel?: string,
  contextInfo?: string,
  specificTags?: string,
): void {
  // implementation...
}

// Valid usages
sentryException()
sentryException(undefined, undefined, 'tag')
sentryException('a', 'b', 'tag')

// Invalid usages
sentryException('a')
sentryException('a', undefined, 'tag')

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

Update ngModel value following the PUT request response

I currently have a variable named dummy_value and I would like to update it using an input box. <p>{{dummy_value}}</p> <input [(ngModel)]="dummy_value" /> Upon making this change, the dummy_value updates instantly due to the two-way bin ...

What causes the error message when attempting to assign an argument of type 'any[]' to a parameter expecting type 'never'?

I encountered the following error in this code: Argument of type 'any[]' is not assignable to parameter of type 'never' var markers: []; this.Getlapoints(this.map.getCenter(), 500000).then(data => { for (var key in data) { ...

A guide on applying color from an API response to the border-color property in an Angular application

When I fetch categoryColor from the API Response, I set border-left: 3px solid {{element.categoryColor}} in inline style. Everything is functioning correctly with no development issues; however, in Visual Studio, the file name appears red as shown in the i ...

How to implement SVG in React with the image source as a parameter?

I've been working on a React component in NextJS that displays an image inside a hexagon. The issue I'm facing is that when I try to use multiple instances of this component with different images in the HexagonWall, all hexagons end up displaying ...

Stepper that is vertical combined with table information

I am currently facing a unique challenge with a component I'm trying to create. It's a combination of a vertical Stepper and a Datagrid. My goal is to group specific table sections within the content of a vertical Stepper, purely for data visual ...

Encountering issues with vite build due to @types/react-router-dom package

I ran into an issue while developing my react app using Vite and TypeScript. Everything works fine when using Vite for development, but as soon as I switch to "tsc && vite build", I encounter numerous errors from @types/react-router-dom and @types/react-ro ...

Troubles encountered while fetching URL parameters in Angular 2

Currently in the process of setting up a confirmation email system for my Angular 2 application with a .NET Core 2 backend. The flow goes like this: user registers -> an email is sent to confirm their account -> they click the link -> they should ...

Broadcasting events across the entire system

I'm trying to accomplish something specific in Angular2 - emitting a custom event globally and having multiple components listen to it, not just following the parent-child pattern. Within my event source component, I have: export class EventSourceCo ...

I encountered an issue where TypeScript does not recognize the type of a variable resulting from object destructuring

I'm attempting to utilize a variable from a destructuring expression as part of another object, but Typescript is not correctly recognizing its type. Here is an example of what I am trying to achieve: // defining a data structure type Data = { fir ...

The type definition file for '@types' is not present in Ionic's code base

After updating my Ionic 6 project to use Angular 3, everything works perfectly in debug mode. However, when I attempt to compile for production using 'ionic build --prod' or 'ionic cordova build android --prod', I encounter the followin ...

Vue.js with TypeScript: The property 'xxx' is not found on the type 'never'

I have a computed method that I am trying to execute: get dronesFiltered(){ const filtered = this.drones.filter((drone) => { return drone.id.toString().indexOf(this.filterId) > -1 && drone.name.toLowerCase().toString().in ...

Nested arrays in an Angular interface

As a newcomer to Angular with a background in Java, I am accustomed to setting up classes as data structures for my information. However, after doing some research, I have learned that interfaces should be used instead. I am facing an issue understanding ...

Is there a universal method to transform the four array values into an array of objects using JavaScript?

Looking to insert data from four array values into an array of objects in JavaScript? // Necessary input columnHeaders=['deviceName','Expected','Actual','Lost'] machine=['machine 1','machine 2&apo ...

Adding connected types to a list using Typescript

Question regarding Typescript fundamentals. In my code, I have a list that combines two types using the & operator. Here is how it's initialized: let objects: (Object & number)[] = []; I'm unsure how to add values to this list. I attem ...

Adjusting the interface of a third-party TypeScript library

I am currently working on modifying a third-party interface. I'm curious about why this particular code is successful: import { LoadableComponentMethods as OldLoadableComponentMethods } from '@loadable/component'; declare module "load ...

An error occurred while trying to access properties of null, specifically the `_rawValidators` property

I recently upgraded an app from angular 8 to angular14 and encountered a problem with a form array. The error message I'm seeing is cfs-detail.component.html:13 ERROR TypeError: Cannot read properties of null (reading '_rawValidators'). It ...

Why can't Angular iterate through objects using ngFor in Typescript?

Here's what I currently have: public posts: QueryRef<PostsInterface>; this.posts = this._postService.get(); //in ngOnInit In my HTML file, it looks like this: <mat-card *ngFor="let post of posts | async"> This allows me to display eac ...

Unit testing with Jest in TypeScript for mocking Express and Mongoose

I've been struggling to find comprehensive resources on using jest.fn() to mock TypeScript classes and their methods, like express' Request, Response, NextFunction, and the save() method on a mongoose model. For instance, suppose I have the foll ...

What is the best way to generate a switch statement based on an enum type that will automatically include a case for each enum member?

While Visual Studio Professional has this feature, I am unsure how to achieve it in VS Code. Take for instance the following Colors enum: enum Colors { Red, Blue, When writing a switch statement like this: function getColor(colors: Colors) { swi ...

A long error occurred while using the payloadaction feature of the Redux Toolkit

import { createSlice, PayloadAction, createAsyncThunk } from "@reduxjs/toolkit" import axios, { AxiosError} from "axios" type user = { id: number, token: string } export type error = { error: string } interface authState { user: user | ...