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
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.
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.
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.
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.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With