DEV Community

Discussion on: Understanding Advanced Concepts in Typescript

Collapse
 
negue profile image
negue

Nice examples for typescript concepts :), these do help a lot, depending on how your datastructures are!!

I wanted to add an optimized way of adding properties/fields to your classes:

Instead of this:

class Dog
{
    age: number
    breed: string    

    constructor(age: number, breed: string) 
    {
        this.age = age
        this.breed = breed
    }    

    getRelativeAge(): number
    {
        return this.age * 7
    }
}

you can shorten the code/constructor and use this:

class Dog
{
    // depending if those are private or public, here public
    constructor(public age: number, public breed: string) 
    {
    }    

    getRelativeAge(): number
    {
        return this.age * 7
    }
}

that way you don't need to code these parts yourself and with that have one / more lines where you can't make potential bugs :) - so win/win 🎉