Andrei Zhytkevich Andrei Zhytkevich - 3 months ago 6
TypeScript Question

Define class members in a simple/minified way

I have pretty big class definition with ~15 fields in my Angular 2 project.

class Employee {
private id: number;
private name: string;
private department: string;
private title?: string;
// 10 more fields

constructor(_id: number,
_name: string,
_department: string,
_title: string
// 10 more input parameters
) {
this.id = _id;
this.name = _name;
this.department = _department;
this.title = _title;
// 10 more assignments
}
}


This looks and works correctly, but with all 15 fields it's getting ridiculously long: 3 lines per each class member.

Is there a way to simplify/minify the definition and still be able to create an object using
new
? Like this:

let person1 = new Employee(1, 'Andrei', 'Dev', 'Developer')


Update: I found a solution.

class Employee {
constructor(private id: number,
private name: string,
private department: string,
private title: string
// 10 more input parameters
) {
}
}


When declaring an input for
constructor
with access specifier (
public
or
private
) it does two thing:


  1. Creates a member variable

  2. Assigns an input value



I've never seen it in the official Typescript docs which is weird.

I found it in Angular 2 docs https://angular.io/docs/ts/latest/guide/forms.html. However, I doubt, that it's related specifically to Angular2.

Update2: More complete and up-to-date Typescript documentation https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md#8.3.1 (thanks to torazaburo)

Answer

The solution is to add an access specifies (private, public or protected) in front of variables in constructor:

class Employee {
    constructor(private id: number,
                private name: string,
                private department: string,
                private title: string
                // 10 more input parameters
                ) {
    }
}

It does two thing:

  1. Creates a member variable
  2. Assigns an input value

I've never seen it in the official Typescript docs which is weird.

I found it in Angular 2 docs https://angular.io/docs/ts/latest/guide/forms.html. However, I doubt, that it's related specifically to Angular2.

More complete and up-to-date Typescript documentation https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md#8.3.1 (thanks to torazaburo)

Comments