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

Optional members

We can define optional class properties and methods by appending the ? character at the end of the name of a property or method. This behavior is like the behavior that we observed in Chapter 3, Working with Functions, when we learned how to use the ? character to declare optional arguments in a function.

The following code snippet defines a class named Vector with an optional property named z. When we define a Vector instance using numeric values for the properties x and y, the Vector has two dimensions. When we define a Vector instance using numeric values for the properties x, y, and z, the Vector has three dimensions:

class Vector { 
 
    public constructor( 
        public x: number, 
        public y: number, 
        public z?: number 
    ) {} 
 
    public is3D() { 
        return this.z !== undefined; 
    } 
 
    public is2D() { 
        return this.z === undefined; 
    } 
 
} 

The following code snippet declares a Vector instance using only two constructor arguments. As a result, the optional property, z, will be undefined:

const vector2D = new Vector(0, 0); 
vector2D.is2D(); // true 
vector2D.is3D(); // false 
 
const lenght1 = Math.sqrt( 
    vector2D.x * vector2D.x + 
    vector2D.y * vector2D.y + 
    vector2D.z * vector2D.z // Error 
); 

The following code snippet declares a Vector instance using three constructor arguments. As a result, the optional property, z, will be defined:

const vector3D = new Vector(0, 0, 0); 
vector3D.is2D(); // false 
vector3D.is3D(); // true 
 
const lenght2 = Math.sqrt( 
    vector3D.x * vector3D.x + 
    vector3D.y * vector3D.y + 
    ((vector3D.z !== undefined) ? (vector3D.z * vector3D.z) : 0) // OK 
);