Comp 110 Optional Parameters

Optional Parameters

We can make a parameter optional by adding a ? after their names. However, it must always be declared after other parameters. Also if we do elect to make a parameter optional we have to examine whether its type is undefined or number/string/boolean/reference type.

One really helpful time to use optional parameters is with classes! Let's look at a Dog class.

class Dog {    
    age: number;        
    name: string;    
    favoriteToy: string;    
    constructor(age: number, name: string, favoriteToy?: string) {        
        this.age = age;        
        this.name = name;        
        if (favoriteToy !== undefined) {            
            this.favoriteToy = favoriteToy;        
        }    
    }
}

This way we can declare a variable type as that of a Dog without necessarily having to know it's favoriteToy property at first.

let poodle: Dog = new Dog(7, "Lucky");
let chihuahua: Dog = new Dog(4, "Osita", "squeaky bone");

poodle and chihuahua are both valid Dog variables! However, if we tried to access poodle's favoriteToy property we would find that it was undefined.