0

Below JavaScript constructor,

function Person(){
    this.name = arguments[0];
    this.age = arguments[1];
}

let a: Person = new Person('Name1');
let b: Person = new Person('Name2', 20);

let d1: Date = new Date(0); // this works
let d2: Date = new Date(2012, 11); // this works

use arguments object to receive variable number of arguments.

tsc compiler says:

# tsc file.ts
file.ts(6,9): error TS2350: Only a void function can be called with the 'new' keyword.
file.ts(6,9): error TS2554: Expected 0 arguments, but got 1.
file.ts(7,9): error TS2350: Only a void function can be called with the 'new' keyword.
file.ts(7,9): error TS2554: Expected 0 arguments, but got 2

How to pass variable number of arguments to JavaScript constructor?

5
  • 2
    The ES6 way would be function Person(...args) { this.firstName = args[0]; this.lastName = args[1]; } for example. I don't know if TypeScript supports this syntax. Commented May 9, 2018 at 15:23
  • @cdhowie How Date(msec), Date(2012, 11) handles variable number of arguments? In ES5 Commented May 9, 2018 at 15:24
  • 2
    They either (1) access the arguments array as in your first example, or (2) are an internal type provided by the runtime and aren't subject to JavaScript's rules. Either way, JavaScript runtimes don't run their base library through the TypeScript compiler. Note that TypeScript is what's complaining here, not JavaScript. If you take out the TypeScript fluff in your first example, it will run just fine as JavaScript. Your question title and text are misleading; this question isn't about JavaScript at all; it's about TypeScript annotation for variable-argument functions. Commented May 9, 2018 at 15:28
  • 2
    JavaScript happily accepts any number of arguments for a function (just as you have shown in your code). However, that doesn’t mean typescript will allow it (whiteout proper annotation). Commented May 9, 2018 at 15:29
  • related : stackoverflow.com/questions/12739149/… Commented May 9, 2018 at 15:29

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.