Combining the Parameter Properties shorthand with Destructuring in TypeScript Combining the Parameter Properties shorthand with Destructuring in TypeScript typescript typescript

Combining the Parameter Properties shorthand with Destructuring in TypeScript


If you have access to Object.assign, this works:

class PersonData {  firstName: string  constructor(args : PersonData) {    Object.assign(this, args)  }}class Person extends PersonData{}

But note new instances will be populated by anything in args--you can't strip out just the keys you want to use.


There isn't currently a way to do this short-hand, so the closest you can get is to declare the properties longhand and assign the variables from the destructuring assignment:

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;    }}

If you are doing that... you'll probably just decide to accept an IPerson and assign its members without using destructuring in the constructor at all.


Another strategy is to use the ability to assign to a variable of a different name. This cuts down on one repetition in the constructor.

class Person {    firstName: string;    lastName: string;    age: number;    constructor(args: { firstName: string, lastName: string, age: number, }) {        ({            firstName: this.firstName,            lastName: this.lastName,            age: this.age,        } = args);    }}

You can also move one of the definitions in the constructor to an interface.

interface PersonConstructorArgs {    firstName: string;    lastName: string;    age: number;}class Person {    firstName: string;    lastName: string;    age: number;    constructor(args: PersonConstructorArgs) {        ({            firstName: this.firstName,            lastName: this.lastName,            age: this.age,        } = args);    }}

This will be useful when you have a hierarchy.

interface PersonConstructorArgs {    firstName: string;    lastName: string;    age: number;}class Person {    firstName: string;    lastName: string;    age: number;    constructor(args: PersonConstructorArgs) {        ({            firstName: this.firstName,            lastName: this.lastName,            age: this.age,        } = args);    }}interface EmployeeConstructorArgs extends PersonConstructorArgs {    manager: Person;}class Employee extends Person {    manager: Person;    constructor(args: EmployeeConstructorArgs) {        super(args);        ({            manager: this.manager,        } = args);    }}