Learning TypeScript 2.x
上QQ阅读APP看书,第一时间看更新

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 errors in the preceding code snippet by modifying the normalize method so that it returns a new vector (instead of modifying the original vector):

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(); 
        return new Vector3( 
            this.x * len, // OK 
            this.y * len, // OK 
            this.z * len  // OK 
        ); 
    } 
 
}