Skip to Content
Learning TypeScript 2.x - Second Edition
book

Learning TypeScript 2.x - Second Edition

by Remo H. Jansen
April 2018
Beginner content levelBeginner
536 pages
13h 21m
English
Packt Publishing
Content preview from Learning TypeScript 2.x - Second Edition

Read-only properties

The readonly keyword is a modifier that can be applied to the properties of a class. When a property declaration includes a readonly modifier, assignments to the property can only take place as part of the declaration or in a constructor in the same class.

The following example showcases how the readonly modifier prevents assignments to the  x, y, and z properties:

class Vector3 { 
 
    public constructor( 
        public readonly x: number, 
        public readonly y: number, 
        public readonly z: number 
    ) {} 
 
    public length() { 
        return Math.sqrt( 
            this.x * this.x + 
            this.y * this.y + 
            this.z * this.z 
        ); 
    } 
 
    public normalize() { 
        let len = 1 / this.length(); 
        this.x *= len; // Error 
        this.y *= len; // Error 
        this.z *= len; // Error 
    } 
 
} 

We can fix the compilation ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Mastering TypeScript - Fourth Edition

Mastering TypeScript - Fourth Edition

Nathan Rozentals
Learning TypeScript

Learning TypeScript

Josh Goldberg
TypeScript for Beginners

TypeScript for Beginners

Bharath Thippireddy

Publisher Resources

ISBN: 9781788391474Supplemental Content