Default parameters

TypeScript gives us another feature to cope with the scenario depicted earlier in the form of default parameters, where we can set a default value that the parameter will assume when not explicitly populated upon executing the function. The syntax is pretty straightforward, as we can see when we refactor the previous example here:

function greetMe(name: string, greeting: string = 'Hello'): string {
return `${greeting}, ${name}`;
}

Just as with optional parameters, default parameters must be put right after the non-default parameters in the function signature. There is a very important difference, which is that default parameters are always safe to use. Why they are safe to use, is indicated by the ES5 code below. The ES5 code below is the resulting code from compiling the above TypeScript to ES5. The following code indicates that the compiler adds an IF clause that checks whether the variable greeting is undefined and if so gives it a starter value:

function greetMe(name, greeting){
if (greeting === void 0) { greeting = 'Hello'; }

return greeting + ', ' + name;
}

As you can see, the compiler adds an if-clause investigating your value and if it is not set, it adds the value you provided earlier.

The type is inferred when you are dealing with default parameters as you assign a value to them. In the preceding code snippet, greeting is inferred to be a string by it being assigned the string value 'Hello'.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset