Union Types

Union Types Union types are closely related to intersection types, but they are used very differently. Occasionally, you’ll run into a library that expects a parameter to be either a number or a string. For instance, take the following function: /** * Takes a string and adds "padding" to the left. * If 'padding' is a string, then 'padding' is appended to the left side. * If 'padding' is a number, then that number of spaces is added to the left side. */ function padLeft(value: string, paddin

Red flags

Red flags

Dependencies on Modules

Dependencies on Modules If your library depends on a module, use an import statement: import * as moment from "moment"; function getThing(): moment;

Add TypeScript code

Add TypeScript code Right click on scripts and click New Item. Then choose TypeScript File (it may be in the .NET Core section) and name the file app.ts.

hasInstance

Symbol.hasInstance A method that determines if a constructor object recognizes an object as one of the constructor’s instances. Called by the semantics of the instanceof operator.

Dependencies on Global Libraries

Dependencies on Global Libraries If your library depends on a global library, use a /// <reference types="..." /> directive: /// <reference types="someLib" /> function getThing(): someLib.thing;

Mixins

Introduction Along with traditional OO hierarchies, another popular way of building up classes from reusable components is to build them by combining simpler partial classes. You may be familiar with the idea of mixins or traits for languages like Scala, and the pattern has also reached some popularity in the JavaScript community. Mixin sample In the code below, we show how you can model mixins in TypeScript. After the code, we’ll break down how it works. // Disposable Mixin class Disposable {

Consuming Dependencies

Consuming Dependencies There are several kinds of dependencies you might have.

Embedding Expressions

Embedding Expressions JSX allows you to embed expressions between tags by surrounding the expressions with curly braces ({ }). var a = <div> {["foo", "bar"].map(i => <span>{i / 2}</span>)} </div> The above code will result in an error since you cannot divide a string by a number. The output, when using the preserve option, looks like: var a = <div> {["foo", "bar"].map(function (i) { return <span>{i / 2}</span>; })} </div>

Minimal project

Minimal project Let’s start out with a new directory. We’ll name it proj for now, but you can change it to whatever you want. mkdir proj cd proj To start, we’re going to structure our project in the following way: proj/ +- src/ +- dist/ TypeScript files will start out in your src folder, run through the TypeScript compiler and end up in dist. Let’s scaffold this out: mkdir src mkdir dist