What is the reason behind TypeScript condition type not functioning properly with optional parameters?

I am trying to determine if the first argument of a function is optional. Here is what I have written:

type F1 = (payload?: number) => null;
type Res1 = F1 extends (a?: any) => any ? 1 : 2; // result: 1
type Res2 = F1 extends (a: any) => any ? 1 : 2; // result: 1, but expecting 2

type F2 = (payload: number) => null;
type Res3 = F2 extends (a?: any) => any ? 1 : 2; // result: 1, but expecting 2
type Res4 = F2 extends (a: any) => any ? 1 : 2; // result: 1

All of the results are equal to 1. Why is this the case and how can I achieve my desired outcome?

Answer №1

The term 'extends' can be interpreted as 'is assignable to'.

type F1 = (payload?: number) => null;
type Res2 = F1 extends (a: any) => any ? 1 : 2; // expected result is 1, but getting 2

Are (payload?: number) => null and (a: any) => any compatible? Let's delve into this:

// It works fine
const res2: (a: any) => any = (payload?: number) => null;

(a: any) => any allows any value for a, even if it's undefined or a number stated by payload. Hence, we confirm that (payload?: number) => null is indeed assignable. Therefore, F1 extends (a: any) => any should return true and yield 1.

Alternatively, you can make the function arguments optional using Partial, verifying if the resulting arguments are still assignable to the original ones:


type ArgumentType<F extends (...args: any) => any> = F extends (...args: infer A) => any ? A : never;

type FirstArgumentOptional<F extends (...args: any) => any> =
    Partial<ArgumentType<F>> extends ArgumentType<F>
        ? true 
        : false


type T1 = FirstArgumentOptional<(a: any) => any>; // false
type T2 = FirstArgumentOptional<(a?: any) => any>; // true
type T3 = FirstArgumentOptional<() => any>; // true

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

Category of ambiguous attributes

I am currently working on developing a class that will store values for rows and columns, with each row/column identified by a string. I have provided some code below as an example: class TMatrix<TYPE>{ [idRow: string]: { [idCol: string]: TYPE ...

Solving the problem of cookieParser implementation in NestJS

Greetings! I have a question for you. Currently, I am working on developing a backend using NestJS, a Node.js framework. Everything is functioning smoothly except for some issues when it comes to hosting. I have created a new NestJS project and made some ...

Nested asynchronous functions in TypeScript

profile.page.ts: username: string; totalScore: number; ... loadUserData() { this.spinnerDialog.show(); this.firebaseServie.loadUserData().then(() => { this.username = this.sessionData.getUser().getUsername(); this.totalSco ...

Retrieve an enumeration from a value within an enumeration

In my coding project, I have an enum called Animals and I've been working on a function that should return the value as an enum if it is valid. enum Animals { WOLF = 'wolf', BADGER = 'badger', CAT = 'cat', } cons ...

Tips for asynchronously updating a model in TypeScript

I have been working on a function to hide the element for connecting to Facebook upon successful connection. I have implemented two functions, success and error, which trigger after Firebase successfully logs in the user. While I can confirm that these fun ...

Angular Dynamic CSS Library by BPNM

I'm currently working with the Bpmn library to create a diagram. However, I've encountered an issue where I need to hide the palette in the diagram view dynamically. I attempted to achieve this by using @ViewChild in my TypeScript file to target ...

Is there a way to determine the specific child property types of a custom Generic type extension?

I am looking to create a function that can retrieve a property from an extended generic type. Is this something achievable? Here is my attempt: interface Animal { readonly weight: {total: number} } interface Dog extends Animal { readonly weight: ...

Using the moment library in Angular to convert date and time can sometimes lead to errors

Whenever I attempt to convert a Gregorian date to a Persian date, the minute value in the conversion ends up becoming an error. For instance, let's say I want to convert this specific date and time to a Persian date: 2020-09-14T16:51:00+04:30 should ...

What is the key to mastering any concept in Angular2 for optimal results?

When creating a Pipe to filter data, I often use the datatype any, allowing for flexibility with types. However, I have some questions regarding this approach: Is it considered a best practice? Does it impact performance when handling large amounts of da ...

Enhance your images with the Tiptap extension for customizable captions

click here for image description I am looking to include an image along with an editable caption using the tiptap extension Check out this link for more information I found a great example with ProseMirror, but I'm wondering if it's possible ...

Utilizing Input Data from One Component in Another - Angular4

As a newcomer to Angular, I'm facing an issue where I need to access a variable from ComponentA in ComponentB. Here's the code snippet that demonstrates what I'm trying to achieve (I want to utilize the "favoriteSeason" input result in the " ...

Error encountered when using a connected component in Typescript with Redux

Seeking assistance on integrating state from redux into properties within a react component that is outlined in a tsx file. The LoggedInUserState type has been defined elsewhere and is exported as shown below: import { Action, Reducer } from 'redux& ...

Asynchronous handling of lifecycle hooks in TypeScript for Angular and Ionic applications

I'm intrigued by the idea of integrating TypeScript's async/await feature with lifecycle hooks. While this feature is undeniably convenient, I find myself wondering if it's considered acceptable to make lifecycle hooks asynchronous. After ...

Rxjs: Making recursive HTTP requests with a condition-based approach

To obtain a list of records, I use the following command to retrieve a set number of records. For example, in the code snippet below, it fetches 100 records by passing the pageIndex value and increasing it with each request to get the next 100 records: thi ...

What is the best way to transmit a JSON object to REST services using Angular?

Whenever I attempt to send the JSON object to REST services, I encounter an error that looks like this: http://localhost:8080/api/v1/cardLimit 400 (Bad Request); JSON Object Example: public class GameLimit implements Serializable { private stati ...

Use various onChange functions for sliding toggle

I need assistance with a toggle app I'm developing that includes two slide toggles. Even though I have separate onChange() methods for each toggle, toggling one slide-toggle also changes the value of the other slide toggle. The toggle state is saved i ...

Is it possible to access the passed arguments in the test description using jest-each?

Utilizing TypeScript and Jest, consider this sample test which can be found at https://jestjs.io/docs/api#testeachtablename-fn-timeout it.each([ { numbers: [1, 2, 3] }, { numbers: [4, 5, 6] } ])('Test case %#: Amount is $numbers.length =&g ...

Navigating through a multidimensional array in Angular 2 / TypeScript, moving both upwards and downwards

[ {id: 1, name: "test 1", children: [ {id: 2, name: "test 1-sub", children: []} ] }] Imagine a scenario where you have a JSON array structured like the example above, with each element potenti ...

I'm having some trouble with my middleware test in Jest - what could be going wrong?

Below is the middleware function that needs testing: export default function validateReqBodyMiddleware(req: Request, res: Response, next: NextFunction) { const { name, email }: RequestBody = req.body; let errors: iError[] = []; if (!validator.isEmai ...

Mastering the art of duplicating an array of objects in TypeScript

I attempted the following strategy: this.strategies = []; this.strategiesCopy = [...this.strategies]; Unfortunately, it appears this method is not effective as it results in duplicates. ...