Open
Description
Today, we can take advantage of parameter properties to reduce the boilerplate, e.g:
class Person {
constructor(public firstName: string, public lastName: number, public age: number) {
}
}
Since 1.5, we can also use destructuring, e.g:
class Person {
firstName: string;
lastName: string;
age: number;
constructor({ firstName, lastName, age } : { firstName: string, lastName: string, age: number }) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
}
I've tried in many ways to combine both features, but had no success. So:
- Is it possible to combine them nowadays, and if yes, how?
- If not, could it be an improvement to a future TypeScript version? E.g:
class Person {
constructor(public { firstName, lastName, age } : { firstName: string, lastName: string, age: number }) {
}
}
// the code above would possibly transpile to:
var Person = (function () {
function Person(_a) {
var firstName = _a.firstName, lastName = _a.lastName, age = _a.age;
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
return Person;
})();
Activity
xLama commentedon Oct 20, 2015
I like this.
DanielRosenwasser commentedon Oct 20, 2015
@buzinas I originally had this working in #1671, but didn't take it in (check out #1541). I think the issue was that it was relatively dense in semantics. I don't necessarily agree, but maybe someone else on the team can weigh in.
danquirk commentedon Oct 20, 2015
Note that in those proposals the parameter property modifier applied to the entire binding pattern (simpler) as opposed to the original suggestion here which in theory supports different visibility modifiers per destructured element (not sure that level of specificity would be worth it).
buzinas commentedon Oct 20, 2015
@danquirk For me, if it's easier for you to do the other way, I don't really care. In fact, that was my first try (e.g
public {firstName, lastName, age}
), and as soon as it didn't work, I tried to use on each property, and it didn't work too.It would be great if we could support both (since not always we want to create properties for all the parameters, and when we want, it would be simpler to use
public
/private
only once), but if it's easier to support only one approach, it will be great already.Probably it's something that people will use more and more, since destructuring is awesome.
robianmcd commentedon Nov 26, 2015
just ran into this. I think either approach would satisfy most use cases. Hope to see this in a future version.
laurelnaiad commentedon Dec 23, 2015
The first thing I tried was:
Something like this would be a nice-to-have.
jack-guy commentedon Feb 26, 2016
Definitely +1 this. The alternative tends to be... bulky.
albertywu commentedon Mar 23, 2016
👍
hrundik commentedon Apr 19, 2016
👍
aliatsis commentedon Apr 27, 2016
+1
lekev commentedon May 13, 2016
+1
andriilazebnyi commentedon Jun 13, 2016
+1
117 remaining items