{"id":4129,"date":"2016-05-14T03:05:00","date_gmt":"2016-05-14T03:05:00","guid":{"rendered":"http:\/\/www.garysieling.com\/blog\/?p=4129"},"modified":"2016-05-14T03:05:00","modified_gmt":"2016-05-14T03:05:00","slug":"typescript-cast-example","status":"publish","type":"post","link":"https:\/\/www.garysieling.com\/blog\/typescript-cast-example\/","title":{"rendered":"Typescript Cast Example"},"content":{"rendered":"<p>To start off, Typescript doesn&#8217;t have a cast in the way you&#8217;d expect coming from other languages:<\/p>\n<pre lang=\"javascript\">\n\nclass Car {\n}\n\nclass BMW extends Car {\n  fast() {\n  }\n}\n\nlet example: Car = new BMW();\n\n((BMW)example).fast();\n<\/pre>\n<p>The way you do this correctly is quite neat:<\/p>\n<pre lang=\"javascript\">\nif (example instanceof BMW) {\n  example.fast();\n}\n<\/pre>\n<p>The if statement auto-casts the variable you&#8217;re using (if you try to get too fancy with this, you&#8217;ll end up breaking the if statement into multiple nested statements).<\/p>\n<p>If you use primitive types, you use &#8220;typeof&#8221; instead of &#8220;instanceof&#8221;, but otherwise it works the same:<\/p>\n<pre lang=\"javascript\">\nif (typeof first === 'number') {          \n  console.log(x + 1);\n}        \n<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>A demonstration of how &#8220;casting&#8221; works in Typescript<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[4],"tags":[302,557],"aioseo_notices":[],"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/www.garysieling.com\/blog\/wp-json\/wp\/v2\/posts\/4129"}],"collection":[{"href":"https:\/\/www.garysieling.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.garysieling.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.garysieling.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.garysieling.com\/blog\/wp-json\/wp\/v2\/comments?post=4129"}],"version-history":[{"count":0,"href":"https:\/\/www.garysieling.com\/blog\/wp-json\/wp\/v2\/posts\/4129\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.garysieling.com\/blog\/wp-json\/wp\/v2\/media?parent=4129"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.garysieling.com\/blog\/wp-json\/wp\/v2\/categories?post=4129"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.garysieling.com\/blog\/wp-json\/wp\/v2\/tags?post=4129"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}