Close

TypeScript - Parameter Properties

[Last Updated: Aug 31, 2018]

Parameter properties let us create and initialize member variables in one place. It is a shorthand for creating member variables.

So far we have been doing this:

class Person{
    private _name: string;
    private _age: number;
    constructor(name: string, age: number) {
        this._name = name;
        this._age = age;
    }
 ...
}

This can be replaced with parameter properties like this:

class Person {
    constructor(private _name: String, private _age: number) {
    }
...
}

Complete Example

class Person {
    constructor(private _name: string, private _age: number) {
    }

    get name(): string {
        return this._name;
    }

    set name(value: string) {
        this._name = value;
    }

    get age(): number {
        return this._age;
    }

    set age(value: number) {
        this._age = value;
    }
}

let person: Person = new Person("Ashlee", 29);
console.log(person);

Output

Person { _name: 'Ashlee', _age: 29 }

Compiled JavaScript (--target es6):

class Person {
    constructor(_name, _age) {
        this._name = _name;
        this._age = _age;
    }
    get name() {
        return this._name;
    }
    set name(value) {
        this._name = value;
    }
    get age() {
        return this._age;
    }
    set age(value) {
        this._age = value;
    }
}
let person = new Person("Ashlee", 29);
console.log(person);

Example Project

Dependencies and Technologies Used:

  • TypeScript 3.0.1
Parameter Properties Example Select All Download
  • typescript-parameter-properties
    • parameter-properties-example.ts

    See Also