Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Public rest parameters in constructor

i watched a tutorial of typescript, that uses Version 1.0.0. There was a sample of a class, using a public rest parameter in the constructor:

class XYZ {
   constructor(public firstname: string, public lastname: string, ...public emails: Array<string>) {
    }
}

How to do this in Version 1.5.0? If i define the class like this, i got several errors:

type.ts(14,75): error TS1005: '=' expected.
type.ts(14,81): error TS1005: ',' expected.
type.ts(14,88): error TS1005: '=' expected.
type.ts(14,96): error TS1109: Expression expected.

Thanks Mario

like image 501
Mario Semper Avatar asked Apr 17 '15 11:04

Mario Semper


People also ask

What are rest parameters?

The rest parameter syntax allows a function to accept an indefinite number of arguments as an array, providing a way to represent variadic functions in JavaScript.

How do you write rest parameters?

To declare a rest parameter, you prefix the parameter name with three dots and use the array type as the type annotation: function fn(... rest: type[]) { //... } In this example, the getTotal() calculates the total of numbers passed into it.

What happens if you do not use rest parameter as a last argument?

Note: The rest parameter have to be the last argument, as its job is to collect all the remaining arguments into an array. So having a function definition like the code below doesn't make any sense and will throw an error.

What is ES6 rest parameter?

The rest parameter is introduced in ECMAScript 2015 or ES6, which improves the ability to handle parameters. The rest parameter allows us to represent an indefinite number of arguments as an array. By using the rest parameter, a function can be called with any number of arguments.


1 Answers

There is an oversight in the spec, but the rest parameter can't be public or private. Here is how to fix the code:

class XYZ {
    public emails: string[];
    constructor(public firstName: string, public lastName: string, ...emails: string[]) {
        this.emails = emails;
    }
}
like image 114
Paleo Avatar answered Nov 07 '22 03:11

Paleo