Wednesday, July 25, 2018

TypeScript Fields

Just like regular OOP classes, you can define fields in a Typescript class. On the next section are samples on how you define them.

By default access modifiers on the fields are public, however you can explicitly set it to private or public.


class SampleFields {
id: number;
name: string;
description: string;
}

On the above example, field types are explicitly set.

A similar C# class would look like the following:

public class SampleFields
{
    public int id;
    public string name;
    public string description;
}

Do note that type can be inferred:

class SampleFields {
id = 0;
name = "";
description = "";
}


Fields can also be defined on the constructor:

class SampleFields {
constructor (public id = 0, public name = "", public description = "") {
}
}
or
class SampleFields {
constructor (public id: number, public name: string, public description: string) {
}
}

This is called shorthanding

The following statement would only set the fields as local to the constructor block, thus is different from the examples above.

class SampleFields {
constructor (id: number, name: string, description: string) {
}
}

Do note that when accessing class scoped fields, we need to use the this keyword

class SampleFields {
constructor (public id: number, public name: string, public description: string) {
}

setFields() {
this.id = 1;
this.name = "SomeName";
this.description = "Some Description";
}
}


This is it for Typescript fields for now, do leave me a comment if you have corrections or questions.

K, Bye!