Creating a function that utilizes a default argument derived from a separate argument

Consider this JavaScript function:

function foo({ a, b, c = a + b }) {
  return c * 2;
}

When attempting to add type annotations in TypeScript like so:

function foo({ a, b, c = a + b }: { a?: number, b?: number, c: number }): number {
  return c * 2;
}

An error is encountered:

TS2532 Object is possibly undefined
. This error occurs because the types of a and b are not specified as mandatory when c is not provided.

Various methods to specify this constraint were tried, but encountered issues:

  1. Overloading (1):
function foo({ a, b, c = a + b }: { a: number; b: number; c: number }): number;
function foo({ c }: { c: number }): number {
  return c * 2;
}

Error received:

TS2371: A parameter initializer is only allowed in a function or constructor implementation.

  1. Overloading (2):
function foo({ c }: { c: number }): number;
function foo({ a, b, c = a + b }: { a: number; b: number; c: number }): number {
  return c * 2;
}

Error received:

TS2394: This overload signature is not compatible with its implementation signature.

This discrepancy in compatibility is puzzling, as it seems that they should be compatible.

  1. Conditionals
function foo({
  a,
  b,
  c = a + b,
}: {
  a: typeof c extends number ? void : number;
  b: typeof c extends number ? void : number;
  c: typeof a extends number ? void : typeof b extends number ? void : number;
}): number {
  return c * 2;
}

Errors occured:

TS2502: 'a' is referenced directly or indirectly in its own type annotation.
TS2502: 'c' is referenced directly or indirectly in its own type annotation.

These errors make sense since TypeScript struggles with recursive references.

If anyone has insights on how to strongly type this function, please share.

Note: Altering the function's prototype for a different argument structure is acknowledged, but not desired for this exercise.

Answer №1

Consider the following proposition involving union types:

type AB_Defined = {
    a: number,
    b: number,
    c?: number,
}

type AB_Nullable = {
    a?: never,
    b?: never,
    c: number,
}

type FunctionParameters = AB_Defined | AB_Nullable

// In this scenario, I am utilizing a! and b! to specify that they cannot be undefined
function bar({ a, b, c = a! + b! }: FunctionParameters) {
  return c * 2;
}

bar({ a: 3, b: 2 });

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

Enhance the functionality of a module by incorporating plugins when Typescript definitions are divided into multiple files

During my exploration of Typescript 2.2, I encountered a challenge in defining a module for HapiJS with various plugin options. To streamline the core code, I split it into multiple .d.ts files and then imported and re-exported them all from the index.d.t ...

Typescript custom react hook - toggling with useToggle

I developed a custom hook to toggle boolean values: import { useState } from 'react'; export function useToggle(initialValue: boolean) { const [value, setValue] = useState<boolean>(initialValue); const toggleValue = () => setValue ...

How to fix the TS4090 error regarding conflicting definitions for a node in Visual Studio 2017

My TypeScript project is building and running, but I'm encountering a multitude of build errors all originating from one issue: TS4090: (TS) Conflicting definitions for 'node' found at 'C:/[projectpath]/node_modules/@types/node/index ...

Expanding a class in Angular 2

I am attempting to enhance a method within the Angular package available at this link. import { Component, OnInit, Injectable } from '@angular/core'; import { FILE_UPLOAD_DIRECTIVES, FileUploader } from 'ng2-file-upload'; @Injectable ...

Angular correctly displaying specific array items within button elements

I am facing an issue with my dashboard where I have 4 items in an array and 4 buttons on display. My goal is to assign each item with a specific button, but currently, it shows 4 buttons for each "hero" resulting in a total of 16 buttons. I have tried usin ...

Automatic completion of absolute paths in VS Code with the ability to click and view definitions through the configuration file js/tsconfig.json

In order to ensure that absolute paths function correctly, I have found that there are two key steps involved: the compilation process and configuring the code editor. I successfully managed the compilation aspect by utilizing babel-plugin-module-resolver ...

Unidentified file: Error reading property 'filename'

I have a function that retrieves the file name. The file name is displayed in an input field, but the background color of the input field is only visible when a file is selected and the file name is populated there. I would like the background color to b ...

Typescript monorepo facing issues with module resolution in Next.js projects

In my monorepo with yarn workspaces, I have 2 Next.js projects set up. apps ┣ app-1 ┗ app-2 The problem arises when app-1 needs to import components from app-2. I add app-2 as a dependency in the app-1 project and configure the path in app-1's ...

Ways to populate missing cells with a default hyphen symbol

Looking for a way to default empty cells in my primeng datatable to '-'. Consider the following data: [ { 'column': null }, { 'column': { 'name': 'A' } }, { 'column': { 'name': ...

IDE flags an error with TypeScript type declarations

Here is how my type definition looks: export type AuthType = boolean | { roles: string[]; assistant?: string[] } | (() => void); Now, I need to check the type of the auth variable and assign a value or execute a function in this line of code: req.all ...

Transform HTML elements within an *ngFor iteration based on a specific variable in Angular 4

In my current project using Angular 4, I am faced with the task of dynamically modifying HTML tags within an *ngFor loop based on a variable. Here is the code snippet that represents my approach: <mat-card-content *ngFor="let question of questionGrou ...

TypeScript introduces a new `prop` method that handles missing keys in objects

Is there a way to create a prop function that can return a default type if the specified key is not found in object o? type Prop = <K, O extends {}>(k: K, o: O) => K extends keyof O ? O[K] : 'Nah'; /* Argument of type 'K ...

A guide to implementing localStorage in TypeScript

When attempting to assign the object item to Product using this code: localStorage.setItem("Product", JSON.stringify(item)) The JSON string of item is not properly assigned to Product. Is there a solution to this issue? ...

Book of Tales displaying Emotion Styling upon initial load only

I'm currently working with the styled api provided by emotion in order to create a custom styled button. const StyledButton = styled(Button)` background-color: ${theme.palette.grey['800']}; width: 50; height: 50; &:hover { ba ...

Issue when trying to use both the name and value attributes in an input field simultaneously

When the attribute "name" is omitted, the value specified in "value" displays correctly. However, when I include the required "name" attribute to work with [(ngModel)], the "value" attribute stops functioning. Without using the "name" attribute, an error ...

Experiencing a bug in my express application: TypeError - Unable to access properties of undefined (reading 'prototype')

I've encountered the TypeError: Cannot read properties of undefined (reading 'prototype') error in my javascript file. Despite researching online, it seems that many attribute this issue to importing {response} from express, but I am not doi ...

getStaticProps will not return any data

I'm experiencing an issue with my getStaticProps where only one of the two db queries is returning correct data while the other returns null. What could be causing this problem? const Dash = (props) => { const config = props.config; useEffect(() ...

Why is my npm installation generating an ERESOLVE error specifically linked to karma-jasmine-html-reporter?

Could someone help me understand this dependency error I encountered while running npm install and provide guidance on how to resolve such errors? View Error Screenshot I am currently using Angular 16, the latest stable version. npm ERR! code ERESOLVE ...

Angular 5 is encountering an error with a recursive template, specifically a RangeError stating that the maximum call stack

Hey there, I'm currently utilizing Angular recursive template to represent arrays recursively. The code I've been following is provided in this link. My array is dynamic in nature. <ul> <ng-template #recursiveList let-list> ...

What is the method to access a component from a module that has been imported into the app module?

We are currently working on a project that has the following hierarchy. app/ ├── app.component.html ├── app.component.ts ├── app.module.ts <--moduleA and moduleB is imported here ├── app-routing.module.ts ├── moduleA/ ...