TypeScript Revealed by Dan Maharry

TypeScript Revealed by Dan Maharry

Author:Dan Maharry [Maharry, Dan]
Language: eng
Format: epub, pdf
Tags: Computers, Programming Languages, JavaScript, Software Development & Engineering, Tools
ISBN: 9781430257257
Publisher: Apress
Published: 2013-01-30T05:00:00+00:00


Variations on a Signature

TypeScript functions may take three types of parameters when defined:

Positional parameters

Optional parameters

Rest parameter

Positional Parameters

Positional parameters, declared as paramName[:paramType], which you’ve used exclusively up to now, require you to specify a value for them when you call the procedure:

function CelsiusToFahrenheit(celsius: number): number {

return (celsius * (9 / 5) + 32);

}

Optional Parameters

Optional parameters are declared with a postfix question mark: paramName? [: paramType]. These should be set as the last arguments in a call to a function:

var kelvin: number;

function CelsiusConverter (celsius: number,

calculateKelvinToo?: bool = false): number {

if ( calculateKelvinToo) { kelvin = celsius −273.1; }

return (celsius * (9 / 5) +32);

}

JavaScript doesn’t have an explicit hasValue method as C# does to check whether an optional parameter has been given a value. The best way to overcome this is to specify a default value for the parameter. If the function is called without a value assigned to the optional parameter, it is given the default value.

function CelsiusConverter (celsius: number,

calculateKelvinToo?: bool = false ): number {

...

}

If you’d prefer not to assign a default value, you can check whether a parameter has been given a value by comparing it to null and undefined:

var kelvin: number;

function CelsiusConverter (celsius: number,

calculateKelvinToo?: bool): number {

if ( calculateKelvinToo !== null && calculateKelvinToo !== undefined ) {

if ( calculateKelvinToo) { kelvin = celsius −273.1; }

}

return (celsius * (9 / 5) +32);

}

Note that in this example, we take advantage of the fact that functions can access variables outside their scope, to make up for the fact that TypeScript/JavaScript has no equivalent to an out parameter in .NET.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.