Basics

Challenges

Classes

Cookies

Debugging

Events

External Files

Flow Control

Forms

Functions

Html Elements

Installation

Interfaces

Keywords

Modules

Namespaces

Operators

Reference Files

String

Types

TypeScript - Class Properties

In TypeScript, properties can look more like c# fully-implemented properties. Notice in the Constructor, we do NOT get the private fields but instead, the properties themselves.

Just as in most OOP languages, we have Getters and Setters. In TypeScript, properties are really just "keyword" methods/functions which are implicitly public.

You don't have to use getters and setters but if do, you can implement business logic and rules. Notice that with getters and setters, the name of the methods ARE the property names. Ex: get designationCode() and set designationCode. See example 3.

The getter ("get") should accept any arguments and will return the property's value. The setter ("set") will accept the value of property as an argument.

TypeScript doesn't really have a concept of fields vs properties. They're all properties. It's just up to you to expose them publicly or privately.

Whenever you want to refer to a class member that belongs to the class you're in you need to prefix the reference to the member with this followed by a period. this.MyMethod()


// Example 1
class Quarter
{
    // fields
    private _coinValue : number = 0.25;

    // properties
    // This one is read only
    get ValueOfCoin()
    {
        return this._coinValue;
    }
}

// in this document
window.onload = function ()
{
    let quarter = new Quarter();
    let demo = document.getElementById("demo");
    demo.innerHTML = quarter.ValueOfCoin;
};


// Exmaple 2
class Developer
{
    department: string;
    private _title: string;

    // notice the use of getters and setters
    get title(): string
    {
        return this._title;
    }

    set title(newTitle: string)
    {
        this._title = newTitle.toUpperCase();
    }
}

// Example 3
class Spaceship
{
    // fields
    private _designationCode: string;

    // properties - these are what you want expose publicly.
get designationCode(): string
    { return this._designationCode; }
set designationCode(value: string)
    {
        if ((value == undefined) || (value === ""))
        {
            value = "Designation Code needed.";
            throw "Designation Code needed.";
        }
        else
        {
            this._designationCode = value;
        }
    }

    // constructor
    constructor(DesignationCode: string, etc..)
    {
        this.designationCode = DesignationCode;
        ...etc
    }
}

Example 1