Home > Mobile >  how to use multiple optional arguments in typescript
how to use multiple optional arguments in typescript

Time:10-27

In my typescript/node.js code, I have a function with two optional parameters as follows:

export const func1 = (num: Number, name: string, obj?: Params, credentials?: Credentials) => {

where Params is something user-defined, and Credentials is from import { Credentials } from '@aws-sdk/types';

However, when I call func1 as follows:

func1(
      1,
      'Stack',
      {
        name: 'Stack',
        age: 14,
      },
      credentials
    );

where credentials is of type Credentials I get an error saying that func1 expected 2-3 arguments, but got 4 - I can understand why this would happen if only one optional argument was allowed, but does anyone know how I can include 2 optional arguments for func1?

CodePudding user response:

In TypeScript (and JavaScript for that matter), number and Number are two different things. Whereas number is the type for a normal integer or floating point, Number is a constructor used to initialise a new integer or floating point with the number type. So, you can change it to this:

export const func1 = (num: number, name: string, obj?: Params, credentials?: Credentials) => {}

and all should work as planned.

CodePudding user response:

Solved it - just a matter of running yarn build after adding the new optional argument

  • Related