{"id":4126,"date":"2016-05-14T02:59:59","date_gmt":"2016-05-14T02:59:59","guid":{"rendered":"http:\/\/www.garysieling.com\/blog\/?p=4126"},"modified":"2016-05-14T02:59:59","modified_gmt":"2016-05-14T02:59:59","slug":"typescript-type-example","status":"publish","type":"post","link":"https:\/\/www.garysieling.com\/blog\/typescript-type-example\/","title":{"rendered":"Typescript: OR type example"},"content":{"rendered":"<p>In Typescript, you may see a variable declared with a pipe &#8211; this looks like an &#8220;or&#8221; in Javascript. These are termed &#8220;union types&#8221;:<\/p>\n<pre lang=\"javascript\">\nlet y : string | number | SomeClass;\n\ny = 7;\ny = 'abcdef';\ny = new SomeClass();\n<\/pre>\n<p>This is a pretty neat feature. Any common functions are available (e.g. toString). The TypeScript type system uses Duck Typing to establish coherence between types: <\/p>\n<pre lang=\"javascript\">\nalert(y.toString());\n<\/pre>\n<p>If you use non-primitive types, you can use instanceof, like you would in Java or C#:<\/p>\n<pre lang=\"javascript\">\nif (y instanceof SomeClass) {\n  SomeClass.someFunction();      \n}\n<\/pre>\n<p>For primitive detection, you can do a cast and a type check simultaneously:<\/p>\n<pre lang=\"javascript\">\nif (typeof x === \"number\") {\n  console.log(x + 1;\n}\n<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Another example of union types 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\/4126"}],"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=4126"}],"version-history":[{"count":0,"href":"https:\/\/www.garysieling.com\/blog\/wp-json\/wp\/v2\/posts\/4126\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.garysieling.com\/blog\/wp-json\/wp\/v2\/media?parent=4126"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.garysieling.com\/blog\/wp-json\/wp\/v2\/categories?post=4126"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.garysieling.com\/blog\/wp-json\/wp\/v2\/tags?post=4126"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}