A parameter in Typescript must be provided if another parameter is set to true

Need help with TypeScript function parameters:

myFunction(allData: Array<any>, selectedItems: Array<any>, onlyValues: boolean = false, values: Array<any>) {
    console.log(allData);
    console.log(selectedData);
    console.log(onlyValues);
    console.log(values);
}

If onlyValues is true, I want values to be mandatory; otherwise, it's optional. How can I achieve this?

Answer №1

If you're looking for a safer approach, consider using a guarded type:

type Data = {onlyData: true, data: Array<any>} | {onlyData: false}

When calling the function, pass in

(allData: Array<any>, selectedItems: Array<any>, d: Data)
.

Experiment with this concept on the TypeScript Playground.

Answer №2

In a type, you have the option to explicitly assign a value for a parameter, such as onlyValues, where it can be set to true in one case and false in another.

type Props = {
  allData: Array<any>, selectedItems: Array<any>, onlyValues: true, values: Array<any>
}

type PropsWithoutValues = {
  allData: Array<any>, selectedItems: Array<any>, onlyValues: false
}

function myFunction(props: Props | PropsWithoutValues) {
    console.log(props.allData);
    console.log(props.selectedItems);
    console.log(props.onlyValues);
    if (props.onlyValues) {
      console.log(props.values);
    }
}

Feel free to experiment with this code in the TS Playground.

Answer №3

If you want to provide multiple signatures for a function, you can utilize function overloading:

function myFunction(allData: Array<any>, selectedItems: Array<any>, onlyValues: true, values: Array<any>): void
function myFunction(allData: Array<any>, selectedItems: Array<any>, onlyValues: false): void
function myFunction(allData: Array<any>, selectedItems: Array<any>, onlyValues: boolean, values?: Array<any>): void {
    if (onlyValues) {
        // When running the function, `values` should be provided but it's not always guaranteed
        // Check for its existence and handle cases where it may be missing
        console.log(values);
    }

    console.log(allData);
    console.log(selectedItems);
    console.log(onlyValues);
}

myFunction([1, 2, 3], [1, 3], true);                 // error, when `values` is not included, `onlyValues` should be false
myFunction([1, 2, 3], [1, 3], true, ['a', 'b']);     // OK, `onlyValues` === true, `value` is provided
myFunction([1, 2, 3], [1, 3], false);                // OK, `onlyValues` === false, `value` is not required
myFunction([1, 2, 3], [1, 3], false, ['a', 'b']);    // error, `onlyValues` === false, `value` should not be included

Visit the TypeScript playground for more information.

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 it possible for recursive type definitions to handle generics effectively?

I have identified what I believe to be a bug in Typescript and have submitted it as an issue here. Considering that this might not get resolved quickly, I am reaching out for suggestions. Does anyone know of a better solution or workaround than the one pro ...

Tips for sidestepping the need for casting the class type of an instance

Looking to develop a function that can accept an argument containing a service name and return an instance of that particular service, all while ensuring proper typing. Casting the instance seems necessary in order to achieve the desired result. To illust ...

Having trouble locating the name 'angular' in TypeScript error message

I have completed all the necessary settings, such as adding the typescript compiler in webstorm and installing tsd with npm. However, I am still encountering an error stating 'Cannot find name Angular'. tsd.json { "version": "v4", "repo": ...

Selecting options in combobox for each row in a table using Angular 2 programmatically

I am currently working on an Angular 2 application using TypeScript. In one of the tables within the application, there is a select control in one of the columns. The contents of this select control are bound to another string array. <table ngContr ...

Building a filter for a union type in TypeScript: a step-by-step guide

Allow me to present an example to demonstrate my current objective. const v1: { type: "S"; payload: string } = { type: "S", payload: "test" }; const v2: { type: "N"; payload: number } = { type: "N", payload: 123 }; type Actions = typeof v1 | typeof v2; ...

Picture is currently not displaying within a NextJS element

A question arises in my Firebase web app regarding the NextJS component below: import Link from "next/link"; import Image from 'next/image' import "./displayShop.css"; import telImg from '../images/Telephone.png'; ...

Guide to leveraging clsx within nested components in React

I am currently using clsx within a React application and encountering an issue with how to utilize it when dealing with mappings and nested components. For instance: return ( <div> <button onClick={doSomething}>{isOpened ? <Component ...

Implementing a back button in an RTL layout with Ionic 2

Just starting an Ionic 2 app in Arabic language requires a RTL layout. I decided to go with the side menu template. Adding the following line for configuring the app to RTL perfectly changed everything's direction, except for the back button which st ...

The 'type' property is not found on the 'never' type

There seems to be a typescript error showing up as Error: Property 'type' does not exist on type 'never' in the following code snippet: export const getSomething = (actionLog: [] | undefined) => { console.info(actionLog[length ...

Reactive form loses preloaded data due to ExpressionChangedAfterItHasBeenCheckedError when modal is dismissed

Within my project, I have a sidenav that contains various links. One of these links directs to a component that presents some input data. Below is the TypeScript code: @Input() data: MyData; myModal: BsModalRef; editForm: FormGroup; ngOnInit(){ this. ...

Simulate internationalization for vue using jest

Currently, I am working on setting up jest unit tests for a Vue project within a complex custom monorepo. I am facing an issue with i18n, which I use for translation management in my application. The problem arises with the following code snippet for init ...

The issue with downloading all files in Firefox persists when attempting to download multiple files simultaneously due to an anchor click

I am currently facing an issue with downloading multiple files using TypeScript in Angular 6. I am receiving an array of blobs from a web API service. Here is the service method used to get multiple blobs for downloading: private downloadTest(): void { ...

In the realm of Typescript Angular, transferring the value of an object's property to another property within the

I'm working with a large TypeScript object and I am hoping to automate certain parts of it to streamline my workflow. myObject = [ { id: 0, price: 100, isBought: false, click: () => this.buyItem(100, 0) } buyItem (it ...

Mongoose failing to persist subdocument

After trying to insert into my collection, I noticed that the sub-document is not being saved along with it. This issue has left me puzzled. This is the scheme/model I am working with: import { Schema, Document, Model, model } from 'mongoose' ...

Pass information from a child component to a parent component within a React.js application

Using the Semantic-UI CSS Framework, I have implemented a dropdown menu and want to be able to select an item from it and identify which item has been selected. While I can determine the selected item within the child component and set its state, I am faci ...

Declaration of React conditional props in TypeScript

I am facing an issue with my React component where the type is determined by a runtime variable (isMock). I am struggling to get the TS declarations to function properly: The component can either be MockedProvider or ApolloProvider from @apollo/client, ea ...

Creating a TypeScript declaration file for a singular module

Consider the following directory structure: src/ ├── foo.ts ├── bar.ts ├── baz.ts ├── index.ts If foo.ts, bar.ts, and baz.ts each export a default class or object, for example in foo.ts: export default class Foo { x = 2; } I ...

Tips for transforming or changing Partial<T> into T

I have a variable named Partial<T> in my coding project. returnPartial(): Partial<T> {} proceed(param T) {} //<-- the provided input parameter will always be of type T in this function and cannot be changed let object = this.returnPartial( ...

Switch on a single component of map array utilizing react and typescript

I am currently working on mapping a reviews API's array and I encountered an issue where all the reviews expand when I click on "read more" instead of just showing the clicked review. Since I am new to TypeScript, I'm not sure how to pass the ind ...

Issue with Next.js hook: Uncaught TypeError - Unable to define properties of undefined (setting 'type')

Encountered an error while attempting to build my nextjs app. Strangely, this error wasn't present in the previous version of the app. I didn't make any changes to the config files, just added a few animation libraries and that's all, along ...