{"id":41532,"date":"2016-10-13T16:05:06","date_gmt":"2016-10-13T10:35:06","guid":{"rendered":"http:\/\/www.tothenew.com\/blog\/?p=41532"},"modified":"2017-02-12T19:21:17","modified_gmt":"2017-02-12T13:51:17","slug":"typescript-a-primer","status":"publish","type":"post","link":"https:\/\/www.tothenew.com\/blog\/typescript-a-primer\/","title":{"rendered":"TypeScript &#8211; A Primer"},"content":{"rendered":"<p>The evolution of JavaScript from merely a scripting language\u00a0to a general purpose programming \u00a0language is indicative of the <a title=\"Yes we too have laws like physics in JavaScript\" href=\"https:\/\/blog.codinghorror.com\/the-principle-of-least-power\/\" target=\"_blank\">Atwood Law<\/a>.\u00a0JavaScript is a multi-paradigm <em>object based<\/em> language with roots in <strong>C<\/strong>, <strong>Java<\/strong>, <strong>Self<\/strong> and <strong>Scheme<\/strong>.\u00a0It was designed to be relaxed i.e. without a static type system. This in my opinion is a perfect rationale for a scripting language &#8211; \u00a0more so if you are designing such a thing in weeks time; my respect to Brendan Eich.<\/p>\n<p>However, the web today is not the same as it was before and evolution demands civilization. <a href=\"https:\/\/www.typescriptlang.org\/\">TypeScript<\/a> is Microsoft&#8217;s forte for JavaScript&#8217;s civilization, adding nothing more but syntactic sugar &#8211; <em>developers on insulin be fore warned<\/em> &#8211; for static typing to meet the need(s) (<em>Microsoft does not provide reference to this need!<\/em>) of <a title=\"Angular developers\" href=\"http:\/\/www.tothenew.com\/front-end-angularjs-development\">JavaScript teams<\/a> that build and maintain large scale JavaScript applications.<\/p>\n<p>This blog is a primer to TypeScript, just enough sugar to make you mobile &#8211; not agile &#8211; so that you can, like me, understand the code written by other in TypeScript, and write your\u00a0own code too. So let&#8217;s begin.<\/p>\n<h3>It&#8217;s all about types<\/h3>\n<p>Types in TypeScript are an extension over that provided by JavaScript.\u00a0We have<\/p>\n<ul>\n<li><code>boolean<\/code> for booleans<\/li>\n<li><code>number<\/code> for numbers &#8211; decimal, hexa, octa, binary<\/li>\n<li><code>string<\/code> for strings<\/li>\n<li><code>enum<\/code> for enumerative values<\/li>\n<li><code>any<\/code> for unrestrictive type and many more &#8230;<\/li>\n<\/ul>\n<p>We annotate a variable with its type while declaration. The grammar for this construct is <em>&lt;scope identifier&gt; &lt;variable identifier&gt; : &lt;type identifier&gt;<\/em>. Here&#8217;s how we do that in code:<\/p>\n<p>[code lang=&#8221;js&#8221;]<br \/>\n &#8212;&#8212; scope identifier (e.g. var, let)<br \/>\n|    \t &#8212;&#8212; variable identifier<br \/>\n|   \t| \t\t \t  \t\t &#8212;&#8212; type identifier<br \/>\n|   \t| \t\t\t \t\t|<br \/>\nvar isJavaScriptAwesome: boolean;<br \/>\nconst withoutAnyDoubt: boolean = true;<br \/>\nlet isTypeScriptASuperSetOfJavaScript : boolean = false;<\/p>\n<p>function echo(sayTheWords: string) {<br \/>\n\t\/\/ All (wo)men must die!<br \/>\n}<\/p>\n<p>echo(&#8216;Valar Morghulis&#8217;);<\/p>\n<p>isJavaScriptAwesome = withoutAnyDoubt;<br \/>\n\/\/ This will be a TypeScript compiler error though<br \/>\nisJavaScriptAwesome = 20<br \/>\n[\/code]<\/p>\n<p>Although the last statement is a compiler error, it will be processed and a valid JavaScript file will be generated as there is no notion of types inherent to the language. However, this definitely help developers in discovering and avoiding author time errors that previously were discoverable only during run time.<\/p>\n<p>We can similarly define the structure of our JavaScript code through TypeScript&#8217;s rich type vocabulary. The TypeScript compiler will try to infer the structure of JavaScript code and provide valuable hints, tooling in terms of intellisense, code-completion, warnings and\/or error\u00a0etc, through mechanism dubbed as <em><strong>duck typing<\/strong><\/em>. Here&#8217;s how we can define type for an object using <code>interface<\/code>s provided by TypeScript.<\/p>\n<p>[code lang=&#8221;js&#8221;]<br \/>\n\/**<br \/>\nDefining structure for a Person object. The object:<br \/>\n &#8211; must have a `name` key which can only be assigned a string values<br \/>\n &#8211; can have an optional(see ? mark) `age` key of type number<br \/>\n &#8211; must have an `address` key the type of which is not known or not restricted by the compiler<br \/>\n*\/<\/p>\n<p>interface Person {<br \/>\n\tname: string,<br \/>\n\tage?: number,<br \/>\n\taddress: any<br \/>\n}<\/p>\n<p>\/\/ defines a function that accepts an argument of type Person<br \/>\nfunction displayPersonInfo(person: Person) {<br \/>\n\t\/\/ logic to do the magic<br \/>\n}<\/p>\n<p>var p: Person = {<br \/>\n\tname: &#8216;Mr X in Bombay&#8217;,<br \/>\n\taddress: [<br \/>\n\t\t&#8216;A deprecated steet&#8217;,<br \/>\n\t\t&#8216;on lonesome locality&#8217;,<br \/>\n\t\t&#8216;in the vicinity of&#8217;,<br \/>\n\t\t&#8216;erstwhile Bombay&#8217;<br \/>\n\t]<br \/>\n}<\/p>\n<p>displayPersonInfo(p);<\/p>\n<p>\/\/ we can also write<br \/>\ndisplayPersonInfo({<br \/>\n\tname: &#8216;Rocket Singh&#8217;,<br \/>\n\tage: 40,<br \/>\n\taddress: {}<br \/>\n});<\/p>\n<p>\/\/ this is error, required parameter missing<br \/>\ndisplayPersonInfo();<\/p>\n<p>\/\/ this too, this aint quack like a duck!<br \/>\ndisplayPersonInfo({<br \/>\n\tfirstName: &#8216;Rocket&#8217;<br \/>\n});<br \/>\n[\/code]<\/p>\n<p>Now that we have seen a glimpse of the TypeScript&#8217;s vocab, here are some common use cases.<\/p>\n<h3>Defining variable types<\/h3>\n<p>[code lang=&#8221;js&#8221;]<br \/>\nlet amIDumb: boolean = true;<br \/>\nlet binaryDecision: number = 0b01;<br \/>\nlet whatIsTheColorOfSky: string = &#8216;blue&#8217; \/\/ are you sure?<\/p>\n<p>const theNinjas: string[] = [&#8216;Doug Crockford&#8217;, &#8216;Kyle Simpson&#8217;, &#8216;John Resig&#8217;];<br \/>\nconst theSamurais: Array&amp;lt;string&amp;gt; = [&#8216;Ryan Dhal&#8217;, &#8216;Misko&#8217;];<\/p>\n<p>var assignMeAnything: any = &#8216;Typeless in a typed world&#8217;;<br \/>\nassignMeAnything = {};<br \/>\nassignMeAnything = [];<br \/>\nassignMeAnything = 3.14159;<\/p>\n<p>let deVoid: void = null; \/\/ null and undefined are void types<br \/>\ndeVoid = undefined;<br \/>\n[\/code]<\/p>\n<h3>Defining enums<\/h3>\n<p>[code lang=&#8221;js&#8221;]<br \/>\nenum TrafficSignal {<br \/>\n\tGreen,<br \/>\n\tYellow,<br \/>\n\tLight<br \/>\n}<\/p>\n<p>let signal: TrafficSignal;<\/p>\n<p>&#8230; \/\/ some code<\/p>\n<p>if ( signal === TrafficSignal.Green) {<br \/>\n\t\/\/ good to go<br \/>\n} else {<br \/>\n\t\/\/ don&#8217;t risk life over triffle things<br \/>\n}<br \/>\n[\/code]<\/p>\n<h3>Defining types for functions<\/h3>\n<p>[code lang=&#8221;js&#8221;]<br \/>\nfunction funcAlias(argument: type) : returnType {<\/p>\n<p>}<\/p>\n<p>function squareInt(input: number) : number {<br \/>\n\treturn input * input;<br \/>\n}<br \/>\n[\/code]<\/p>\n<h3>Defining structure through interfaces<\/h3>\n<ul>\n<li>\n<h4>Type for objects<\/h4>\n<p>[code lang=&#8221;js&#8221;]<br \/>\ninterface Point {<br \/>\n\tx: number,<br \/>\n\ty: number<br \/>\n}<\/p>\n<p>function printCoordinates(point : Point ) : void {<br \/>\n\tlet pointStr = `(${point.x}, ${point.y})`;<br \/>\n\tconsole.log(pointStr);<br \/>\n}<br \/>\n[\/code]<\/p>\n<\/li>\n<li>\n<h4>Type for functions<\/h4>\n<p>[code lang=&#8221;js&#8221;]<br \/>\n\/\/ a function that works with type T and return boolean; remember generics<br \/>\ninterface Predicate&amp;lt;T&amp;gt; {<br \/>\n\t(item: T) : boolean<br \/>\n}<\/p>\n<p>\/\/ a function that takes an array of T and a predicate of T<br \/>\n\/\/ and return an array of T<br \/>\ninterface Filter&amp;lt;T&amp;gt; {<br \/>\n\t(collection: Array&amp;lt;T&amp;gt;, predicate: Predicate&amp;lt;T&amp;gt; ) : Array&amp;lt;T&amp;gt;;<br \/>\n}<\/p>\n<p>let isEven: Predicate&amp;lt;number&amp;gt;;<br \/>\nisEven = function (arg: number): boolean {<br \/>\n\treturn (arg &amp;amp; 1) == 0;<br \/>\n}<\/p>\n<p>let getEvens: Filter&amp;lt;number&amp;gt;;<br \/>\ngetEvens = function(collection: number[], predicate: Predicate&amp;lt;number&amp;gt;) {<br \/>\n\treturn collection.filter(isEven);<br \/>\n}<\/p>\n<p>console.log( getEvens([1,2,3,4,5,6,7], isEven) );<br \/>\n[\/code]<\/p>\n<\/li>\n<\/ul>\n<p>Similarly we can define interfaces for advanced structures like classes, but that would be too much for a primer. So enjoy the <em> a la carte <\/em> and I <code>promise<\/code> will serve the meal soon.<\/p>\n<p>Do let me know your opinions in the comments.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>The evolution of JavaScript from merely a scripting language\u00a0to a general purpose programming \u00a0language is indicative of the Atwood Law.\u00a0JavaScript is a multi-paradigm object based language with roots in C, Java, Self and Scheme.\u00a0It was designed to be relaxed i.e. without a static type system. This in my opinion is a perfect rationale for a [&hellip;]<\/p>\n","protected":false},"author":939,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"iawp_total_views":5},"categories":[3429,1185,1994,1],"tags":[4860,55,4117],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/41532"}],"collection":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/users\/939"}],"replies":[{"embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/comments?post=41532"}],"version-history":[{"count":0,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/41532\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/media?parent=41532"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/categories?post=41532"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/tags?post=41532"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}