Javascript Default Parameters with TypeScript Tutorial.
Posted by robert | Filed under TypeScript
Another cool thing about TypeScript is the use of default parameters right in the function parameters. Take a look below and see how easy it is. I added them to the addPerson Method/Function but you can also added it to your class constructor. You can see default parameters in the constructor in my other TypeScript Tutorial and look at the Car class.
class Main { constructor() { this.addPerson("Jon"); this.addPerson("Brad", 6); this.addPerson("David", 4.11, 200); this.addPerson("Robert"); } addPerson(name:string, height:number = 5.10, weight:number = 180):void { console.log(name + " is " + height + " tall and weighs " + weight + " pounds.") } }
This will console log out:
Jon is 5.1 tall and weighs 180 pounds. Brad is 6 tall and weighs 180 pounds. David is 5.11 tall and weighs 200 pounds. Robert is 5.1 tall and weighs 180 pounds.
The generated code looks very clean and readable from the TypeScript compiler.
var Main = (function () { function Main() { this.addPerson("Jon"); this.addPerson("Brad", 6); this.addPerson("David", 4.11, 200); this.addPerson("Robert"); } Main.prototype.addPerson = function (name, height, weight) { if (typeof height === "undefined") { height = 5.1; } if (typeof weight === "undefined") { weight = 180; } console.log(name + " is " + height + " tall and weighs " + weight + " pounds."); }; return Main; })();
You can download the code below. Also if you like this tutorial please provide a link back to this page or my site.
December 30, 2012 at 11:01 am
Hey! Thanks alot for your tutorials regarding TypeScript! Really helps!
October 8, 2014 at 6:16 pm
our brains are sore. Instead of always taking this approach, what if we engaged a new part of ourselves
Oakley Flak Jacket Sunglasses http://www.ebuyaccessories.com