# Table of Contents - [README | TypeScript Deep Dive](#readme-typescript-deep-dive) - [Getting Started | TypeScript Deep Dive](#getting-started-typescript-deep-dive) - [Why TypeScript | TypeScript Deep Dive](#why-typescript-typescript-deep-dive) - [JavaScript | TypeScript Deep Dive](#javascript-typescript-deep-dive) - [Equality | TypeScript Deep Dive](#equality-typescript-deep-dive) - [Null vs. Undefined | TypeScript Deep Dive](#null-vs-undefined-typescript-deep-dive) - [References | TypeScript Deep Dive](#references-typescript-deep-dive) - [this | TypeScript Deep Dive](#this-typescript-deep-dive) - [Closure | TypeScript Deep Dive](#closure-typescript-deep-dive) - [Number | TypeScript Deep Dive](#number-typescript-deep-dive) - [Truthy | TypeScript Deep Dive](#truthy-typescript-deep-dive) - [Future JavaScript Now | TypeScript Deep Dive](#future-javascript-now-typescript-deep-dive) - [Rest Parameters | TypeScript Deep Dive](#rest-parameters-typescript-deep-dive) - [Classes Emit | TypeScript Deep Dive](#classes-emit-typescript-deep-dive) - [Classes | TypeScript Deep Dive](#classes-typescript-deep-dive) - [const | TypeScript Deep Dive](#const-typescript-deep-dive) - [Arrow Functions | TypeScript Deep Dive](#arrow-functions-typescript-deep-dive) - [let | TypeScript Deep Dive](#let-typescript-deep-dive) - [Destructuring | TypeScript Deep Dive](#destructuring-typescript-deep-dive) - [for...of | TypeScript Deep Dive](#for-of-typescript-deep-dive) - [Project | TypeScript Deep Dive](#project-typescript-deep-dive) - [Spread Operator | TypeScript Deep Dive](#spread-operator-typescript-deep-dive) - [Template Strings | TypeScript Deep Dive](#template-strings-typescript-deep-dive) - [Async Await | TypeScript Deep Dive](#async-await-typescript-deep-dive) - [Node.js QuickStart | TypeScript Deep Dive](#node-js-quickstart-typescript-deep-dive) - [Which Files? | TypeScript Deep Dive](#which-files-typescript-deep-dive) - [Iterators | TypeScript Deep Dive](#iterators-typescript-deep-dive) - [Library QuickStart | TypeScript Deep Dive](#library-quickstart-typescript-deep-dive) - [Modules | TypeScript Deep Dive](#modules-typescript-deep-dive) - [tsconfig.json | TypeScript Deep Dive](#tsconfig-json-typescript-deep-dive) - [Browser QuickStart | TypeScript Deep Dive](#browser-quickstart-typescript-deep-dive) - [Dynamic Import Expressions | TypeScript Deep Dive](#dynamic-import-expressions-typescript-deep-dive) - [Promise | TypeScript Deep Dive](#promise-typescript-deep-dive) - [Generators | TypeScript Deep Dive](#generators-typescript-deep-dive) - [JSX | TypeScript Deep Dive](#jsx-typescript-deep-dive) - [Options | TypeScript Deep Dive](#options-typescript-deep-dive) - [Errors in TypeScript | TypeScript Deep Dive](#errors-in-typescript-typescript-deep-dive) - [noImplicitAny | TypeScript Deep Dive](#noimplicitany-typescript-deep-dive) - [Testing | TypeScript Deep Dive](#testing-typescript-deep-dive) - [strictNullChecks | TypeScript Deep Dive](#strictnullchecks-typescript-deep-dive) - [React | TypeScript Deep Dive](#react-typescript-deep-dive) - [NPM | TypeScript Deep Dive](#npm-typescript-deep-dive) - [Husky | TypeScript Deep Dive](#husky-typescript-deep-dive) - [Tools | TypeScript Deep Dive](#tools-typescript-deep-dive) - [Prettier | TypeScript Deep Dive](#prettier-typescript-deep-dive) - [Non React JSX | TypeScript Deep Dive](#non-react-jsx-typescript-deep-dive) - [@types | TypeScript Deep Dive](#-types-typescript-deep-dive) - [Interpreting Errors | TypeScript Deep Dive](#interpreting-errors-typescript-deep-dive) - [Ambient Declarations | TypeScript Deep Dive](#ambient-declarations-typescript-deep-dive) - [Compilation Context | TypeScript Deep Dive](#compilation-context-typescript-deep-dive) - [Common Errors | TypeScript Deep Dive](#common-errors-typescript-deep-dive) - [Interfaces | TypeScript Deep Dive](#interfaces-typescript-deep-dive) - [Callable | TypeScript Deep Dive](#callable-typescript-deep-dive) - [Namespaces | TypeScript Deep Dive](#namespaces-typescript-deep-dive) - [global.d.ts | TypeScript Deep Dive](#global-d-ts-typescript-deep-dive) - [Declaration Spaces | TypeScript Deep Dive](#declaration-spaces-typescript-deep-dive) - [JS Migration Guide | TypeScript Deep Dive](#js-migration-guide-typescript-deep-dive) - [Functions | TypeScript Deep Dive](#functions-typescript-deep-dive) - [Type Assertion | TypeScript Deep Dive](#type-assertion-typescript-deep-dive) - [Freshness | TypeScript Deep Dive](#freshness-typescript-deep-dive) - [Generics | TypeScript Deep Dive](#generics-typescript-deep-dive) - [Literal Types | TypeScript Deep Dive](#literal-types-typescript-deep-dive) - [TypeScript's Type System | TypeScript Deep Dive](#typescript-s-type-system-typescript-deep-dive) - [Moving Types | TypeScript Deep Dive](#moving-types-typescript-deep-dive) - [Readonly | TypeScript Deep Dive](#readonly-typescript-deep-dive) - [Never Type | TypeScript Deep Dive](#never-type-typescript-deep-dive) - [Type Inference | TypeScript Deep Dive](#type-inference-typescript-deep-dive) - [Type Guard | TypeScript Deep Dive](#type-guard-typescript-deep-dive) - [Enums | TypeScript Deep Dive](#enums-typescript-deep-dive) - [TypeScript Compiler Internals | TypeScript Deep Dive](#typescript-compiler-internals-typescript-deep-dive) - [Scanner | TypeScript Deep Dive](#scanner-typescript-deep-dive) - [Mixins | TypeScript Deep Dive](#mixins-typescript-deep-dive) - [TIP: SyntaxKind enum | TypeScript Deep Dive](#tip-syntaxkind-enum-typescript-deep-dive) - [Parser | TypeScript Deep Dive](#parser-typescript-deep-dive) - [Cypress | TypeScript Deep Dive](#cypress-typescript-deep-dive) - [Exception Handling | TypeScript Deep Dive](#exception-handling-typescript-deep-dive) - [Trivia | TypeScript Deep Dive](#trivia-typescript-deep-dive) - [StyleGuide | TypeScript Deep Dive](#styleguide-typescript-deep-dive) - [Currying | TypeScript Deep Dive](#currying-typescript-deep-dive) - [TIPs | TypeScript Deep Dive](#tips-typescript-deep-dive) - [Index Signatures | TypeScript Deep Dive](#index-signatures-typescript-deep-dive) - [Checker | TypeScript Deep Dive](#checker-typescript-deep-dive) - [Stateful Functions | TypeScript Deep Dive](#stateful-functions-typescript-deep-dive) - [Changelog | TypeScript Deep Dive](#changelog-typescript-deep-dive) - [String Based Enums | TypeScript Deep Dive](#string-based-enums-typescript-deep-dive) - [Discriminated Unions | TypeScript Deep Dive](#discriminated-unions-typescript-deep-dive) - [File Module Details | TypeScript Deep Dive](#file-module-details-typescript-deep-dive) - [ESLint | TypeScript Deep Dive](#eslint-typescript-deep-dive) - [lib.d.ts | TypeScript Deep Dive](#lib-d-ts-typescript-deep-dive) - [singleton pattern | TypeScript Deep Dive](#singleton-pattern-typescript-deep-dive) - [JQuery tips | TypeScript Deep Dive](#jquery-tips-typescript-deep-dive) - [Type Compatibility | TypeScript Deep Dive](#type-compatibility-typescript-deep-dive) - [Type Instantiation | TypeScript Deep Dive](#type-instantiation-typescript-deep-dive) - [Function parameters | TypeScript Deep Dive](#function-parameters-typescript-deep-dive) - [Lazy Object Literal Initialization | TypeScript Deep Dive](#lazy-object-literal-initialization-typescript-deep-dive) - [Create Arrays | TypeScript Deep Dive](#create-arrays-typescript-deep-dive) - [Avoid Export Default | TypeScript Deep Dive](#avoid-export-default-typescript-deep-dive) - [Classes are Useful | TypeScript Deep Dive](#classes-are-useful-typescript-deep-dive) - [Barrel | TypeScript Deep Dive](#barrel-typescript-deep-dive) - [Program | TypeScript Deep Dive](#program-typescript-deep-dive) - [Jest | TypeScript Deep Dive](#jest-typescript-deep-dive) - [Checker Error Reporting | TypeScript Deep Dive](#checker-error-reporting-typescript-deep-dive) - [Typesafe Event Emitter | TypeScript Deep Dive](#typesafe-event-emitter-typescript-deep-dive) - [Checker Diagnostics | TypeScript Deep Dive](#checker-diagnostics-typescript-deep-dive) - [Nominal Typing | TypeScript Deep Dive](#nominal-typing-typescript-deep-dive) - [Emitter | TypeScript Deep Dive](#emitter-typescript-deep-dive) - [AST | TypeScript Deep Dive](#ast-typescript-deep-dive) - [Parser Functions | TypeScript Deep Dive](#parser-functions-typescript-deep-dive) - [Declaration Files | TypeScript Deep Dive](#declaration-files-typescript-deep-dive) - [TIP: Visit Children | TypeScript Deep Dive](#tip-visit-children-typescript-deep-dive) - [Emitter SourceMaps | TypeScript Deep Dive](#emitter-sourcemaps-typescript-deep-dive) - [Contributing | TypeScript Deep Dive](#contributing-typescript-deep-dive) - [Variables | TypeScript Deep Dive](#variables-typescript-deep-dive) - [Binder Error Reporting | TypeScript Deep Dive](#binder-error-reporting-typescript-deep-dive) - [Binder Declarations | TypeScript Deep Dive](#binder-declarations-typescript-deep-dive) - [Binder Functions | TypeScript Deep Dive](#binder-functions-typescript-deep-dive) - [Binder | TypeScript Deep Dive](#binder-typescript-deep-dive) - [Binder Container | TypeScript Deep Dive](#binder-container-typescript-deep-dive) - [Binder SymbolTable | TypeScript Deep Dive](#binder-symboltable-typescript-deep-dive) - [static constructors | TypeScript Deep Dive](#static-constructors-typescript-deep-dive) - [Limit Property Setters | TypeScript Deep Dive](#limit-property-setters-typescript-deep-dive) - [Build Toggles | TypeScript Deep Dive](#build-toggles-typescript-deep-dive) - [Emitter Functions | TypeScript Deep Dive](#emitter-functions-typescript-deep-dive) - [outFile caution | TypeScript Deep Dive](#outfile-caution-typescript-deep-dive) --- # README | TypeScript Deep Dive [![YouTube Channel Subscribers](https://basarat.gitbook.io/typescript/~gitbook/image?url=https%3A%2F%2Fimg.shields.io%2Fyoutube%2Fchannel%2Fsubscribers%2FUCGD_0i6L48hucTiiyhb5QzQ%3Fstyle%3Dsocial&width=300&dpr=4&quality=100&sign=ae2c4d2a&sv=2)](https://www.youtube.com/@basarat) [](https://basarat.gitbook.io/typescript#typescript-deep-dive) TypeScript Deep Dive ---------------------------------------------------------------------------------------- Learn Professional TypeScript. I've been looking at the issues that turn up commonly when people start using TypeScript. This is based on the lessons from [Stack Overflow](http://stackoverflow.com/tags/typescript/topusers) / [DefinitelyTyped](https://github.com/DefinitelyTyped/) and general engagement with the [TypeScript community](https://github.com/TypeStrong/) . You can [follow for updates](https://twitter.com/basarat) and [don't forget to โ˜… on GitHub](https://github.com/basarat/typescript-book) ๐ŸŒน ### [](https://basarat.gitbook.io/typescript#reviews) Reviews * Thanks for the wonderful book. Learned a lot from it. ([link](https://www.gitbook.com/book/basarat/typescript/discussions/21#comment-1468279131934) ) * Its probably the Best TypeScript book out there. Good Job ([link](https://twitter.com/thelondonjs/status/756419561570852864) ) * Love how precise and clear the examples and explanations are! ([link](https://twitter.com/joe_mighty/status/758290957280346112) ) * For the low, low price of free, you get pages of pure awesomeness. Chock full of source code examples and clear, concise explanations, TypeScript Deep Dive will help you learn TypeScript development. ([link](https://www.nativescript.org/blog/details/free-book-typescript-deep-dive) ) * Just a big thank you! **Best TypeScript 2 detailed explanation!** ([link](https://www.gitbook.com/book/basarat/typescript/discussions/38) ) * This gitbook got my project going pronto. Fluent easy read 5 stars. ([link](https://twitter.com/thebabellion/status/779888195559235584) ) * I recommend the online #typescript book by @basarat you'll love it.([link](https://twitter.com/markpieszak/status/788099306590969860) ) * I've always found this by @basarat really helpful. ([link](https://twitter.com/Brocco/status/789887640656945152) ) * We must highlight TypeScript Deep Dive, an open source book.([link](https://www.siliconrepublic.com/enterprise/typescript-programming-javascript) ) * Great online resource for learning. ([link](https://twitter.com/rdfuhr/status/790193307708076035) ) * Thank you for putting this book together, and for all your hard work within the TypeScript community. ([link](https://github.com/basarat/typescript-book/pull/183#issuecomment-257799713) ) * TypeScript Deep Dive is one of the best technical texts I've read in a while. ([link](https://twitter.com/borekb/status/794287092272599040) ) * Thanks @basarat for the TypeScript Deep Dive Book. Help me a lot with my first TypeScript project. ([link](https://twitter.com/betolinck/status/797901548562960384) ) * Thanks to @basarat for this great #typescript learning resource. ([link](https://twitter.com/markuse1501/status/799116176815230976) ) * Guyz excellent book on Typescript(@typescriptlang) by @basarat ([link](https://twitter.com/deeinlove/status/813245965507260417) ) * Leaning on the legendary @basarat's "TypeScript Deep Dive" book heavily at the moment ([link](https://twitter.com/sitapati/status/814379404956532737) ) * numTimesPointedPeopleToBasaratsTypeScriptBook++; ([link](https://twitter.com/brocco/status/814227741696462848) ) * A book not only for typescript, a good one for deeper JavaScript knowledge as well. [link](https://www.gitbook.com/book/basarat/typescript/discussions/59) * In my new job, we're using @typescriptlang, which I am new to. This is insanely helpful huge thanks, @basarat! [link](https://twitter.com/netchkin/status/855339390566096896) * Thank you for writing TypeScript Deep Dive. I have learned so much. [link](https://twitter.com/buctwbzs/status/857198618704355328?refsrc=email&s=11) * Loving @basarat's @typescriptlang online book basarat.gitbooks.io/typescript/# loaded with great recipes! [link](https://twitter.com/ericliprandi/status/857608837309677568) * Microsoft doc is great already, but if want to "dig deeper" into TypeScript I find this book of great value [link](https://twitter.com/caludio/status/876729910550831104) * Thanks, this is a great book ๐Ÿค“๐Ÿค“ [link](https://twitter.com/jjwonmin/status/885666375548547073) * Deep dive to typescript is awesome in so many levels. i find it very insightful. Thanks [link](https://twitter.com/orenmizr/status/891083492787970053) * @basarat's intro to @typescriptlang is still one of the best going (if not THE best) [link](https://twitter.com/stevealee/status/953953255968698368) * This is sweet! So many #typescript goodies! [link](https://twitter.com/pauliescanlon/status/989898852474998784) ### [](https://basarat.gitbook.io/typescript#get-started) Get Started If you are here to read the book online [get started](https://basarat.gitbook.io/typescript/getting-started) . ### [](https://basarat.gitbook.io/typescript#translations) Translations Book is completely free so you can copy paste whatever you want without requiring permission. If you have a translation you want me to link here. [Send a PR](https://github.com/basarat/typescript-book/edit/master/README.md) . * [Filipino](https://github.com/themarshann/typescript-book-fil) * [Italian](https://github.com/TizioFittizio/typescript-book) * [Chinese](https://github.com/jkchao/typescript-book-chinese) * [Russian](https://github.com/etroynov/typescript-book) * [Portuguese](https://github.com/overlineink/typescript-book) * [Japanese](https://github.com/yohamta/typescript-book) * [Spanish](https://github.com/melissarofman/typescript-book) * [Korean](https://github.com/radlohead/typescript-book) * [French](https://github.com/HachemiH/typescript-book) * [Polish](https://github.com/mbiesiad/typescript-book/tree/pl_PL) * [Thai](https://github.com/futurouz/typescript-book) * [Bengali](https://github.com/Acesif/typescript-book) * [Ukrainian](https://github.com/ArtfulBits/typescript-book) ### [](https://basarat.gitbook.io/typescript#other-options) Other Options You can also download one of the Epub, Mobi, or PDF formats from the [actions tab](https://github.com/basarat/typescript-book/actions) by clicking on the latest build run. You will find the files in the artifacts section. ### [](https://basarat.gitbook.io/typescript#special-thanks) Special Thanks All the amazing [contributors](https://github.com/basarat/typescript-book/graphs/contributors) ๐ŸŒน Share URL: https://basarat.gitbook.io/typescript/ [NextGetting Started](https://basarat.gitbook.io/typescript/getting-started) Last updated 1 year ago * [TypeScript Deep Dive](https://basarat.gitbook.io/typescript#typescript-deep-dive) * [Reviews](https://basarat.gitbook.io/typescript#reviews) * [Get Started](https://basarat.gitbook.io/typescript#get-started) * [Translations](https://basarat.gitbook.io/typescript#translations) * [Other Options](https://basarat.gitbook.io/typescript#other-options) * [Special Thanks](https://basarat.gitbook.io/typescript#special-thanks) * [Share](https://basarat.gitbook.io/typescript#share) --- # Getting Started | TypeScript Deep Dive * [Getting Started with TypeScript](https://basarat.gitbook.io/typescript/getting-started#getting-started-with-typescript) * [TypeScript Version](https://basarat.gitbook.io/typescript/getting-started#typescript-version) [](https://basarat.gitbook.io/typescript/getting-started#getting-started-with-typescript) Getting Started With TypeScript ------------------------------------------------------------------------------------------------------------------------------ TypeScript compiles into JavaScript. JavaScript is what you are actually going to execute (either in the browser or on the server). So you are going to need the following: * TypeScript compiler (OSS available [in source](https://github.com/Microsoft/TypeScript/) and on [NPM](https://www.npmjs.com/package/typescript) ) * A TypeScript editor (you can use notepad if you want but I use [vscode ๐ŸŒน](https://code.visualstudio.com/) with an [extension I wrote](https://marketplace.visualstudio.com/items?itemName=basarat.god) . Also [lots of other IDES support it as well](https://github.com/Microsoft/TypeScript/wiki/TypeScript-Editor-Support) ) ### [](https://basarat.gitbook.io/typescript/getting-started#typescript-version) TypeScript Version Instead of using the _stable_ TypeScript compiler we will be presenting a lot of new stuff in this book that may not be associated with a version number yet. I generally recommend people to use the nightly version because **the compiler test suite only catches more bugs over time**. You can install it on the command line as Copy npm install -g typescript@next And now the command line `tsc` will be the latest and greatest. Various IDEs support it too, e.g. * You can ask vscode to use this version by creating `.vscode/settings.json` with the following contents: Copy { "typescript.tsdk": "./node_modules/typescript/lib" } ### [](https://basarat.gitbook.io/typescript/getting-started#getting-the-source-code) Getting the Source Code The source for this book is available in the books github repository [https://github.com/basarat/typescript-book/tree/master/code](https://github.com/basarat/typescript-book/tree/master/code) most of the code samples can be copied into vscode and you can play with them as is. For code samples that need additional setup (e.g. npm modules), we will link you to the code sample before presenting the code. e.g. `this/will/be/the/link/to/the/code.ts` With a dev setup out of the way let's jump into TypeScript syntax. [PreviousREADME](https://basarat.gitbook.io/typescript) [NextWhy TypeScript](https://basarat.gitbook.io/typescript/getting-started/why-typescript) Last updated 5 years ago * [Getting Started With TypeScript](https://basarat.gitbook.io/typescript/getting-started#getting-started-with-typescript) * [TypeScript Version](https://basarat.gitbook.io/typescript/getting-started#typescript-version) * [Getting the Source Code](https://basarat.gitbook.io/typescript/getting-started#getting-the-source-code) Copy // This will be the code under discussion --- # Why TypeScript | TypeScript Deep Dive There are two main goals of TypeScript: * Provide an _optional type system_ for JavaScript. * Provide planned features from future JavaScript editions to current JavaScript engines The desire for these goals is motivated below. [](https://basarat.gitbook.io/typescript/getting-started/why-typescript#the-typescript-type-system) The TypeScript type system ----------------------------------------------------------------------------------------------------------------------------------- You might be wondering "**Why add types to JavaScript?**" Types have proven ability to enhance code quality and understandability. Large teams (Google, Microsoft, Facebook) have continually arrived at this conclusion. Specifically: * Types increase your agility when doing refactoring. _It's better for the compiler to catch errors than to have things fail at runtime_. * Types are one of the best forms of documentation you can have. _The function signature is a theorem and the function body is the proof_. However, types have a way of being unnecessarily ceremonious. TypeScript is very particular about keeping the barrier to entry as low as possible. Here's how: ### [](https://basarat.gitbook.io/typescript/getting-started/why-typescript#your-javascript-is-typescript) Your JavaScript is TypeScript TypeScript provides compile time type safety for your JavaScript code. This is no surprise given its name. The great thing is that the types are completely optional. Your JavaScript code `.js` file can be renamed to a `.ts` file and TypeScript will still give you back valid `.js` equivalent to the original JavaScript file. TypeScript is _intentionally_ and strictly a superset of JavaScript with optional Type checking. ### [](https://basarat.gitbook.io/typescript/getting-started/why-typescript#types-can-be-implicit) Types can be Implicit TypeScript will try to infer as much of the type information as it can in order to give you type safety with minimal cost of productivity during code development. For example, in the following example TypeScript will know that foo is of type `number` below and will give an error on the second line as shown: Copy var foo = 123; foo = '456'; // Error: cannot assign `string` to `number` // Is foo a number or a string? This type inference is well motivated. If you do stuff like shown in this example, then, in the rest of your code, you cannot be certain that `foo` is a `number` or a `string`. Such issues turn up often in large multi-file code bases. We will deep dive into the type inference rules later. ### [](https://basarat.gitbook.io/typescript/getting-started/why-typescript#types-can-be-explicit) Types can be Explicit As we've mentioned before, TypeScript will infer as much as it can safely. However, you can use annotations to: 1. Help along the compiler, and more importantly document stuff for the next developer who has to read your code (that might be future you!). 2. Enforce that what the compiler sees, is what you thought it should see. That is your understanding of the code matches an algorithmic analysis of the code (done by the compiler). TypeScript uses postfix type annotations popular in other _optionally_ annotated languages (e.g. ActionScript and F#). So if you do something wrong the compiler will report an error e.g.: We will discuss all the details of all the annotation syntax supported by TypeScript in a later chapter. ### [](https://basarat.gitbook.io/typescript/getting-started/why-typescript#types-are-structural) Types are structural In some languages (specifically nominally typed ones) static typing results in unnecessary ceremony because even though _you know_ that the code will work fine the language semantics force you to copy stuff around. This is why stuff like [automapper for C#](http://automapper.org/) is _vital_ for C#. In TypeScript because we really want it to be easy for JavaScript developers with a minimum cognitive overload, types are _structural_. This means that _duck typing_ is a first class language construct. Consider the following example. The function `iTakePoint2D` will accept anything that contains all the things (`x` and `y`) it expects: ### [](https://basarat.gitbook.io/typescript/getting-started/why-typescript#type-errors-do-not-prevent-javascript-emit) Type errors do not prevent JavaScript emit To make it easy for you to migrate your JavaScript code to TypeScript, even if there are compilation errors, by default TypeScript _will emit valid JavaScript_ the best that it can. e.g. will emit the following js: So you can incrementally upgrade your JavaScript code to TypeScript. This is very different from how many other language compilers work and yet another reason to move to TypeScript. ### [](https://basarat.gitbook.io/typescript/getting-started/why-typescript#types-can-be-ambient) Types can be ambient A major design goal of TypeScript was to make it possible for you to safely and easily use existing JavaScript libraries in TypeScript. TypeScript does this by means of _declaration_. TypeScript provides you with a sliding scale of how much or how little effort you want to put in your declarations, the more effort you put the more type safety + code intelligence you get. Note that definitions for most of the popular JavaScript libraries have already been written for you by the [DefinitelyTyped community](https://github.com/borisyankov/DefinitelyTyped) so for most purposes either: 1. The definition file already exists. 2. Or at the very least, you have a vast list of well reviewed TypeScript declaration templates already available As a quick example of how you would author your own declaration file, consider a trivial example of [jquery](https://jquery.com/) . By default (as is to be expected of good JS code) TypeScript expects you to declare (i.e. use `var` somewhere) before you use a variable As a quick fix _you can tell TypeScript_ that there is indeed something called `$`: If you want you can build on this basic definition and provide more information to help protect you from errors: We will discuss the details of creating TypeScript definitions for existing JavaScript in detail later once you know more about TypeScript (e.g. stuff like `interface` and the `any`). [](https://basarat.gitbook.io/typescript/getting-started/why-typescript#future-javascript-greater-than-now) Future JavaScript => Now ----------------------------------------------------------------------------------------------------------------------------------------- TypeScript provides a number of features that are planned in ES6 for current JavaScript engines (that only support ES5 etc). The TypeScript team is actively adding these features and this list is only going to get bigger over time and we will cover this in its own section. But just as a specimen here is an example of a class: and the lovely fat arrow function: ### [](https://basarat.gitbook.io/typescript/getting-started/why-typescript#summary) Summary In this section we have provided you with the motivation and design goals of TypeScript. With this out of the way we can dig into the nitty gritty details of TypeScript. [PreviousGetting Started](https://basarat.gitbook.io/typescript/getting-started) [NextJavaScript](https://basarat.gitbook.io/typescript/recap) Last updated 5 years ago * [The TypeScript type system](https://basarat.gitbook.io/typescript/getting-started/why-typescript#the-typescript-type-system) * [Your JavaScript is TypeScript](https://basarat.gitbook.io/typescript/getting-started/why-typescript#your-javascript-is-typescript) * [Types can be Implicit](https://basarat.gitbook.io/typescript/getting-started/why-typescript#types-can-be-implicit) * [Types can be Explicit](https://basarat.gitbook.io/typescript/getting-started/why-typescript#types-can-be-explicit) * [Types are structural](https://basarat.gitbook.io/typescript/getting-started/why-typescript#types-are-structural) * [Type errors do not prevent JavaScript emit](https://basarat.gitbook.io/typescript/getting-started/why-typescript#type-errors-do-not-prevent-javascript-emit) * [Types can be ambient](https://basarat.gitbook.io/typescript/getting-started/why-typescript#types-can-be-ambient) * [Future JavaScript => Now](https://basarat.gitbook.io/typescript/getting-started/why-typescript#future-javascript-greater-than-now) * [Summary](https://basarat.gitbook.io/typescript/getting-started/why-typescript#summary) Copy var foo: number = 123; Copy var foo: number = '123'; // Error: cannot assign a `string` to a `number` Copy interface Point2D { x: number; y: number; } interface Point3D { x: number; y: number; z: number; } var point2D: Point2D = { x: 0, y: 10 } var point3D: Point3D = { x: 0, y: 10, z: 20 } function iTakePoint2D(point: Point2D) { /* do something */ } iTakePoint2D(point2D); // exact match okay iTakePoint2D(point3D); // extra information okay iTakePoint2D({ x: 0 }); // Error: missing information `y` Copy var foo = 123; foo = '456'; // Error: cannot assign a `string` to a `number` Copy var foo = 123; foo = '456'; Copy $('.awesome').show(); // Error: cannot find name `$` Copy declare var $: any; $('.awesome').show(); // Okay! Copy declare var $: { (selector:string): any; }; $('.awesome').show(); // Okay! $(123).show(); // Error: selector needs to be a string Copy class Point { constructor(public x: number, public y: number) { } add(point: Point) { return new Point(this.x + point.x, this.y + point.y); } } var p1 = new Point(0, 10); var p2 = new Point(10, 20); var p3 = p1.add(p2); // { x: 10, y: 30 } Copy var inc = x => x+1; --- # JavaScript | TypeScript Deep Dive There were (and will continue to be) a lot of competitors in _Some syntax_ to _JavaScript_ compilers. TypeScript is different from them in that _Your JavaScript is TypeScript_. Here's a diagram: ![](https://basarat.gitbook.io/typescript/~gitbook/image?url=https%3A%2F%2Fraw.githubusercontent.com%2Fbasarat%2Ftypescript-book%2Fmaster%2Fimages%2Fvenn.png&width=768&dpr=4&quality=100&sign=15157563&sv=2) JavaScript is TypeScript However, it does mean that _you need to learn JavaScript_ (the good news is _you_ _**only**_ _need to learn JavaScript_). TypeScript is just standardizing all the ways you provide _good documentation_ on JavaScript. * Just giving you a new syntax doesn't help catch bugs - but might help you write cleaner / less bugs (e.g. CoffeeScript). * Creating a new language abstracts you too far from your runtimes and communities - but might help on-board you easier if its an already familiar flavour (e.g. Dart - closer for Java / C# devs). TypeScript is just JavaScript with docs. > JSNext is open to interpretation - not everything proposed for the next version of JS actually makes it to browsers. TypeScript only adds support for proposals once they reach [stage 3](https://tc39.es/process-document/) > . [](https://basarat.gitbook.io/typescript/recap#making-javascript-better) Making JavaScript Better ------------------------------------------------------------------------------------------------------ TypeScript will try to protect you from portions of JavaScript that never worked (so you don't need to remember this stuff): Essentially TypeScript is linting JavaScript. Just doing a better job at it than other linters that don't have _type information_. [](https://basarat.gitbook.io/typescript/recap#you-still-need-to-learn-javascript) You still need to learn JavaScript -------------------------------------------------------------------------------------------------------------------------- That said TypeScript is very pragmatic about the fact that _you do write JavaScript_ so there are some things about JavaScript that you still need to know in order to not be caught off-guard. Let's discuss them next. > Note: TypeScript is a superset of JavaScript. Just with documentation that can actually be used by compilers / IDEs ;) [PreviousWhy TypeScript](https://basarat.gitbook.io/typescript/getting-started/why-typescript) [NextEquality](https://basarat.gitbook.io/typescript/recap/equality) Last updated 5 years ago * [Making JavaScript Better](https://basarat.gitbook.io/typescript/recap#making-javascript-better) * [You still need to learn JavaScript](https://basarat.gitbook.io/typescript/recap#you-still-need-to-learn-javascript) Copy [] + []; // JavaScript will give you "" (which makes little sense), TypeScript will error // // other things that are nonsensical in JavaScript // - don't give a runtime error (making debugging hard) // - but TypeScript will give a compile time error (making debugging unnecessary) // {} + []; // JS : 0, TS Error [] + {}; // JS : "[object Object]", TS Error {} + {}; // JS : NaN or [object Object][object Object] depending upon browser, TS Error "hello" - 1; // JS : NaN, TS Error function add(a,b) { return a + b; // JS : undefined, TS Error 'unreachable code detected' } --- # Equality | TypeScript Deep Dive [](https://basarat.gitbook.io/typescript/recap/equality#equality) Equality ------------------------------------------------------------------------------- One thing to be careful about in JavaScript is the difference between `==` and `===`. As JavaScript tries to be resilient against programming errors `==` tries to do type coercion between two variables e.g. converts a string to a number so that you can compare with a number as shown below: Copy console.log(5 == "5"); // true , TS Error console.log(5 === "5"); // false , TS Error However, the choices JavaScript makes are not always ideal. For example, in the below example the first statement is false because `""` and `"0"` are both strings and are clearly not equal. However, in the second case both `0` and the empty string (`""`) are falsy (i.e. behave like `false`) and are therefore equal with respect to `==`. Both statements are false when you use `===`. Copy console.log("" == "0"); // false console.log(0 == ""); // true console.log("" === "0"); // false console.log(0 === ""); // false > Note that `string == number` and `string === number` are both compile time errors in TypeScript, so you don't normally need to worry about this. Similar to `==` vs. `===`, there is `!=` vs. `!==` So ProTip: Always use `===` and `!==` except for null checks, which we cover later. [](https://basarat.gitbook.io/typescript/recap/equality#structural-equality) Structural Equality ----------------------------------------------------------------------------------------------------- If you want to compare two objects for structural equality `==`/`===` are _**not**_ sufficient. e.g. Copy console.log({a:123} == {a:123}); // False console.log({a:123} === {a:123}); // False To do such checks use the [deep-equal](https://www.npmjs.com/package/deep-equal) npm package e.g. However, quite commonly you don't need deep checks and all you really need is to check by some `id` e.g. [PreviousJavaScript](https://basarat.gitbook.io/typescript/recap) [NextReferences](https://basarat.gitbook.io/typescript/recap/references) Last updated 5 years ago * [Equality](https://basarat.gitbook.io/typescript/recap/equality#equality) * [Structural Equality](https://basarat.gitbook.io/typescript/recap/equality#structural-equality) Copy import * as deepEqual from "deep-equal"; console.log(deepEqual({a:123},{a:123})); // True Copy type IdDisplay = { id: string, display: string } const list: IdDisplay[] = [\ {\ id: 'foo',\ display: 'Foo Select'\ },\ {\ id: 'bar',\ display: 'Bar Select'\ },\ ] const fooIndex = list.map(i => i.id).indexOf('foo'); console.log(fooIndex); // 0 --- # Null vs. Undefined | TypeScript Deep Dive > [Free youtube video on the subject](https://www.youtube.com/watch?v=kaUfBNzuUAI) JavaScript (and by extension TypeScript) has two bottom types : `null` and `undefined`. They are _intended_ to mean different things: * Something hasn't been initialized : `undefined`. * Something is currently unavailable: `null`. [](https://basarat.gitbook.io/typescript/recap/null-undefined#checking-for-either) Checking for either ----------------------------------------------------------------------------------------------------------- Fact is you will need to deal with both. Interestingly in JavaScript with `==`, `null` and `undefined` are only equal to each other: Copy // Both null and undefined are only `==` to themselves and each other: console.log(null == null); // true (of course) console.log(undefined == undefined); // true (of course) console.log(null == undefined); // true // You don't have to worry about falsy values making through this check console.log(0 == undefined); // false console.log('' == undefined); // false console.log(false == undefined); // false Recommend `== null` to check for both `undefined` or `null`. You generally don't want to make a distinction between the two. Copy function foo(arg: string | null | undefined) { if (arg != null) { // arg must be a string as `!=` rules out both null and undefined. } } > You could also do `== undefined`, but `== null` is more conventional/shorter. One exception, root level `undefined` values which we discuss next. [](https://basarat.gitbook.io/typescript/recap/null-undefined#checking-for-root-level-undefined) Checking for root level undefined --------------------------------------------------------------------------------------------------------------------------------------- Remember how I said you should use `== null`? Of course you do (cause I just said it ^). Don't use it for root level things. In strict mode if you use `foo` and `foo` is undefined you get a `ReferenceError` **exception** and the whole call stack unwinds. > You should use strict mode ... and in fact the TS compiler will insert it for you if you use modules ... more on those later in the book so you don't have to be explicit about it :) So to check if a variable is defined or not at a _global_ level you normally use `typeof`: [](https://basarat.gitbook.io/typescript/recap/null-undefined#limit-explicit-use-of-undefined) Limit explicit use of `undefined` ------------------------------------------------------------------------------------------------------------------------------------- Because TypeScript gives you the opportunity to _document_ your structures separately from values instead of stuff like: you should use a type annotation: [](https://basarat.gitbook.io/typescript/recap/null-undefined#node-style-callbacks) Node style callbacks ------------------------------------------------------------------------------------------------------------- Node style callback functions (e.g. `(err,somethingElse)=>{ /* something */ }`) are generally called with `err` set to `null` if there isn't an error. You generally just use a truthy check for this anyways: When creating your own APIs it's _okay_ to use `null` in this case for consistency. In all sincerity for your own APIs you should look at promises, in that case you actually don't need to bother with absent error values (you handle them with `.then` vs. `.catch`). [](https://basarat.gitbook.io/typescript/recap/null-undefined#dont-use-undefined-as-a-means-of-denoting-validity) Don't use `undefined` as a means of denoting _validity_ ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ For example an awful function like this: can be much better written like this: [](https://basarat.gitbook.io/typescript/recap/null-undefined#json-and-serialization) JSON and serialization ----------------------------------------------------------------------------------------------------------------- The JSON standard has support for encoding `null` but not `undefined`. When JSON-encoding an object with an attribute that is `null`, the attribute will be included with its null value, whereas an attribute with an `undefined` value will be excluded entirely. As a result, JSON-based databases may support `null` values but not `undefined` values. Since attributes set to `null` are encoded, you can transmit the intent to clear an attribute by setting its value to `null` before encoding and transmitting the object to a remote store. Setting attribute values to undefined can save on storage and transmission costs, as the attribute names will not be encoded. However, this can complicate the semantics of clearing values vs. absent values. [](https://basarat.gitbook.io/typescript/recap/null-undefined#final-thoughts) Final thoughts ------------------------------------------------------------------------------------------------- TypeScript team doesn't use `null` : [TypeScript coding guidelines](https://github.com/Microsoft/TypeScript/wiki/Coding-guidelines#null-and-undefined) and it hasn't caused any problems. Douglas Crockford thinks [`null` is a bad idea](https://www.youtube.com/watch?v=PSGEjv3Tqo0&feature=youtu.be&t=9m21s) and we should all just use `undefined`. However, NodeJS style code bases uses `null` for Error arguments as standard as it denotes `Something is currently unavailable`. I personally don't care to distinguish between the two as most projects use libraries with differing opinions and just rule out both with `== null`. [PreviousReferences](https://basarat.gitbook.io/typescript/recap/references) [Nextthis](https://basarat.gitbook.io/typescript/recap/this) Last updated 5 years ago * [Checking for either](https://basarat.gitbook.io/typescript/recap/null-undefined#checking-for-either) * [Checking for root level undefined](https://basarat.gitbook.io/typescript/recap/null-undefined#checking-for-root-level-undefined) * [Limit explicit use of undefined](https://basarat.gitbook.io/typescript/recap/null-undefined#limit-explicit-use-of-undefined) * [Node style callbacks](https://basarat.gitbook.io/typescript/recap/null-undefined#node-style-callbacks) * [Don't use undefined as a means of denoting validity](https://basarat.gitbook.io/typescript/recap/null-undefined#dont-use-undefined-as-a-means-of-denoting-validity) * [JSON and serialization](https://basarat.gitbook.io/typescript/recap/null-undefined#json-and-serialization) * [Final thoughts](https://basarat.gitbook.io/typescript/recap/null-undefined#final-thoughts) Copy if (typeof someglobal !== 'undefined') { // someglobal is now safe to use console.log(someglobal); } Copy function foo(){ // if Something return {a:1,b:2}; // else return {a:1,b:undefined}; } Copy function foo():{a:number,b?:number}{ // if Something return {a:1,b:2}; // else return {a:1}; } Copy fs.readFile('someFile', 'utf8', (err,data) => { if (err) { // do something } else { // no error } }); Copy function toInt(str: string) { return str ? parseInt(str) : undefined; } Copy function toInt(str: string): { valid: boolean, int?: number } { const int = parseInt(str); if (isNaN(int)) { return { valid: false }; } else { return { valid: true, int }; } } Copy JSON.stringify({willStay: null, willBeGone: undefined}); // {"willStay":null} --- # References | TypeScript Deep Dive Beyond literals, any Object in JavaScript (including functions, arrays, regexp etc) are references. This means the following [](https://basarat.gitbook.io/typescript/recap/references#mutations-are-across-all-references) Mutations are across all references --------------------------------------------------------------------------------------------------------------------------------------- Copy var foo = {}; var bar = foo; // bar is a reference to the same object foo.baz = 123; console.log(bar.baz); // 123 [](https://basarat.gitbook.io/typescript/recap/references#equality-is-for-references) Equality is for references --------------------------------------------------------------------------------------------------------------------- Copy var foo = {}; var bar = foo; // bar is a reference var baz = {}; // baz is a *new object* distinct from `foo` console.log(foo === bar); // true console.log(foo === baz); // false [PreviousEquality](https://basarat.gitbook.io/typescript/recap/equality) [NextNull vs. Undefined](https://basarat.gitbook.io/typescript/recap/null-undefined) Last updated 5 years ago * [Mutations are across all references](https://basarat.gitbook.io/typescript/recap/references#mutations-are-across-all-references) * [Equality is for references](https://basarat.gitbook.io/typescript/recap/references#equality-is-for-references) --- # this | TypeScript Deep Dive Any access to `this` keyword within a function is controlled by how the function is actually called. It is commonly referred to as the โ€œcalling context.โ€ Here is an example: Copy function foo() { console.log(this); } foo(); // logs out the global e.g. `window` in browsers let bar = { foo } bar.foo(); // Logs out `bar` as `foo` was called on `bar` So be mindful of your usage of `this`. If you want to disconnect `this` in a class from the calling context use an arrow function, [more on that later](https://basarat.gitbook.io/typescript/future-javascript/arrow-functions) . [PreviousNull vs. Undefined](https://basarat.gitbook.io/typescript/recap/null-undefined) [NextClosure](https://basarat.gitbook.io/typescript/recap/closure) Last updated 5 years ago --- # Closure | TypeScript Deep Dive The best thing that JavaScript ever got was closures. A function in JavaScript has access to any variables defined in the outer scope. Closures are best explained with examples: Copy function outerFunction(arg) { var variableInOuterFunction = arg; function bar() { console.log(variableInOuterFunction); // Access a variable from the outer scope } // Call the local function to demonstrate that it has access to arg bar(); } outerFunction("hello closure"); // logs hello closure! You can see that the inner function has access to a variable (variableInOuterFunction) from the outer scope. The variables in the outer function have been closed by (or bound in) the inner function. Hence the term **closure**. The concept in itself is simple enough and pretty intuitive. Now the awesome part: The inner function can access the variables from the outer scope _even after the outer function has returned_. This is because the variables are still bound in the inner function and not dependent on the outer function. Again let's look at an example: Copy function outerFunction(arg) { var variableInOuterFunction = arg; return function() { console.log(variableInOuterFunction); } } var innerFunction = outerFunction("hello closure!"); // Note the outerFunction has returned innerFunction(); // logs hello closure! [](https://basarat.gitbook.io/typescript/recap/closure#reason-why-its-awesome) Reason why it's awesome ----------------------------------------------------------------------------------------------------------- It allows you to compose objects easily e.g. the revealing module pattern: At a high level it is also what makes something like Node.js possible (don't worry if it doesn't click in your brain right now. It will eventually ๐ŸŒน): [Previousthis](https://basarat.gitbook.io/typescript/recap/this) [NextNumber](https://basarat.gitbook.io/typescript/recap/number) Last updated 5 years ago Copy function createCounter() { let val = 0; return { increment() { val++ }, getVal() { return val } } } let counter = createCounter(); counter.increment(); console.log(counter.getVal()); // 1 counter.increment(); console.log(counter.getVal()); // 2 Copy // Pseudo code to explain the concept server.on(function handler(req, res) { loadData(req.id).then(function(data) { // the `res` has been closed over and is available res.send(data); }) }); --- # Number | TypeScript Deep Dive Whenever you are handling numbers in any programming language you need to be aware of the idiosyncrasies of how the language handles numbers. Here are a few critical pieces of information about numbers in JavaScript that you should be aware of. [](https://basarat.gitbook.io/typescript/recap/number#core-type) Core Type ------------------------------------------------------------------------------- JavaScript has only one number type. It is a double-precision 64-bit `Number`. Below we discuss its limitations along with a recommended solution. [](https://basarat.gitbook.io/typescript/recap/number#decimal) Decimal --------------------------------------------------------------------------- For those familiar with doubles / float in other languages, you would know that binary floating point numbers _do not_ map correctly to Decimal numbers. A trivial (and famous) example with JavaScript's built in numbers is shown below: Copy console.log(.1 + .2); // 0.30000000000000004 > For true decimal math use `big.js` mentioned below. [](https://basarat.gitbook.io/typescript/recap/number#integer) Integer --------------------------------------------------------------------------- The integer limits represented by the built in number type are `Number.MAX_SAFE_INTEGER` and `Number.MIN_SAFE_INTEGER`. Copy console.log({max: Number.MAX_SAFE_INTEGER, min: Number.MIN_SAFE_INTEGER}); // {max: 9007199254740991, min: -9007199254740991} **Safe** in this context refers to the fact that the value _cannot be the result of a rounding error_. The unsafe values are `+1 / -1` away from these safe values and any amount of addition / subtraction will _round_ the result. Copy console.log(Number.MAX_SAFE_INTEGER + 1 === Number.MAX_SAFE_INTEGER + 2); // true! console.log(Number.MIN_SAFE_INTEGER - 1 === Number.MIN_SAFE_INTEGER - 2); // true! console.log(Number.MAX_SAFE_INTEGER); // 9007199254740991 console.log(Number.MAX_SAFE_INTEGER + 1); // 9007199254740992 - Correct console.log(Number.MAX_SAFE_INTEGER + 2); // 9007199254740992 - Rounded! console.log(Number.MAX_SAFE_INTEGER + 3); // 9007199254740994 - Rounded - correct by luck console.log(Number.MAX_SAFE_INTEGER + 4); // 9007199254740996 - Rounded! To check safety you can use ES6 `Number.isSafeInteger`: > JavaScript will eventually get [BigInt](https://developers.google.com/web/updates/2018/05/bigint) > support. For now, if you want arbitrary precision integer math use `big.js` mentioned below. [](https://basarat.gitbook.io/typescript/recap/number#big.js) big.js ------------------------------------------------------------------------- Whenever you use math for financial calculations (e.g. GST calculation, money with cents, addition etc) use a library like [big.js](https://github.com/MikeMcl/big.js/) which is designed for * Perfect decimal math * Safe out of bound integer values Installation is simple: Quick Usage example: > Do not use this library for math used for UI / performance intensive purposes e.g charts, canvas drawing etc. [](https://basarat.gitbook.io/typescript/recap/number#nan) NaN ------------------------------------------------------------------- When some number calculation is not representable by a valid number, JavaScript returns a special `NaN` value. A classic example is imaginary numbers: Note: Equality checks **don't** work on `NaN` values. Use `Number.isNaN` instead: [](https://basarat.gitbook.io/typescript/recap/number#infinity) Infinity ----------------------------------------------------------------------------- The outer bounds of values representable in Number are available as static `Number.MAX_VALUE` and `-Number.MAX_VALUE` values. Values outside the range where precision isn't changed are clamped to these limits e.g. Values outside the range where precision is changed resolve to special values `Infinity`/`-Infinity` e.g. Of-course, these special infinity values also show up with arithmetic that requires it e.g. You can use these `Infinity` values manually or using static members of the `Number` class as shown below: Fortunately comparison operators (`<` / `>`) work reliably on infinity values: [](https://basarat.gitbook.io/typescript/recap/number#infinitesimal) Infinitesimal --------------------------------------------------------------------------------------- The smallest non-zero value representable in Number is available as static `Number.MIN_VALUE` Values smaller than `MIN_VALUE` ("underflow values") are converted to 0. > Further intuition: Just like values bigger than `Number.MAX_VALUE` get clamped to INFINITY, values smaller than `Number.MIN_VALUE` get clamped to `0`. [PreviousClosure](https://basarat.gitbook.io/typescript/recap/closure) [NextTruthy](https://basarat.gitbook.io/typescript/recap/truthy) Last updated 2 years ago * [Core Type](https://basarat.gitbook.io/typescript/recap/number#core-type) * [Decimal](https://basarat.gitbook.io/typescript/recap/number#decimal) * [Integer](https://basarat.gitbook.io/typescript/recap/number#integer) * [big.js](https://basarat.gitbook.io/typescript/recap/number#big.js) * [NaN](https://basarat.gitbook.io/typescript/recap/number#nan) * [Infinity](https://basarat.gitbook.io/typescript/recap/number#infinity) * [Infinitesimal](https://basarat.gitbook.io/typescript/recap/number#infinitesimal) Copy // Safe value console.log(Number.isSafeInteger(Number.MAX_SAFE_INTEGER)); // true // Unsafe value console.log(Number.isSafeInteger(Number.MAX_SAFE_INTEGER + 1)); // false // Because it might have been rounded to it due to overflow console.log(Number.isSafeInteger(Number.MAX_SAFE_INTEGER + 10)); // false Copy npm install big.js @types/big.js Copy import { Big } from 'big.js'; export const foo = new Big('111.11111111111111111111'); export const bar = foo.plus(new Big('0.00000000000000000001')); // To get a number: const x: number = Number(bar.toString()); // Loses the precision Copy console.log(Math.sqrt(-1)); // NaN Copy // Don't do this console.log(NaN === NaN); // false!! // Do this console.log(Number.isNaN(NaN)); // true Copy console.log(Number.MAX_VALUE); // 1.7976931348623157e+308 console.log(-Number.MAX_VALUE); // -1.7976931348623157e+308 Copy console.log(Number.MAX_VALUE + 1 == Number.MAX_VALUE); // true! console.log(-Number.MAX_VALUE - 1 == -Number.MAX_VALUE); // true! Copy console.log(Number.MAX_VALUE + 1e292); // Infinity console.log(-Number.MAX_VALUE - 1e292); // -Infinity Copy console.log( 1 / 0); // Infinity console.log(-1 / 0); // -Infinity Copy console.log(Number.POSITIVE_INFINITY === Infinity); // true console.log(Number.NEGATIVE_INFINITY === -Infinity); // true Copy console.log( Infinity > 1); // true console.log(-Infinity < -1); // true Copy console.log(Number.MIN_VALUE); // 5e-324 Copy console.log(Number.MIN_VALUE / 10); // 0 --- # Truthy | TypeScript Deep Dive JavaScript has a concept of `truthy` i.e. things that evaluate like `true` would in certain positions (e.g. `if` conditions and the boolean `&&` `||` operators). The following things are truthy in JavaScript. An example is any number other than `0` e.g. Copy if (123) { // Will be treated like `true` console.log('Any number other than 0 is truthy'); } Something that isn't truthy is called `falsy`. Here's a handy table for your reference. Variable Type When it is _falsy_ When it is _truthy_ `boolean` `false` `true` `string` `''` (empty string) any other string `number` `0` `NaN` any other number `null` always never `undefined` always never Any other Object including empty ones like `{}`,`[]` never always [](https://basarat.gitbook.io/typescript/recap/truthy#being-explicit) Being explicit ----------------------------------------------------------------------------------------- > The `!!` pattern Quite commonly it helps to be explicit that the intent is to treat the value as a `boolean` and convert it into a _true boolean_ (one of `true`|`false`). You can easily convert values to a true boolean by prefixing it with `!!` e.g. `!!foo`. Its just `!` used _twice_. The first `!` converts the variable (in this case `foo`) to a boolean but inverts the logic (_truthy_ -`!`\> `false`, _falsy_ -`!`\> `true`). The second one toggles it again to match the nature of the original object (e.g. _truthy_ -`!`\> `false` -`!`\> `true`). It is common to use this pattern in lots of places e.g. Copy // Direct variables const hasName = !!name; // As members of objects const someObj = { hasName: !!name } // e.g. in ReactJS JSX {!!someName &&
{someName}
} [PreviousNumber](https://basarat.gitbook.io/typescript/recap/number) [NextFuture JavaScript Now](https://basarat.gitbook.io/typescript/future-javascript) Last updated 5 years ago --- # Future JavaScript Now | TypeScript Deep Dive One of the main selling points of TypeScript is that it allows you to use a bunch of features from ES6 and beyond in current (ES3 and ES5 level) JavaScript engines (like current browsers and Node.js). Here we deep dive into why these features are useful followed by how these features are implemented in TypeScript. Note: Not all of these features are slated for immediate addition to JavaScript but provide great utility to your code organization and maintenance. Also note that you are free to ignore any of the constructs that don't make sense for your project, although you will end up using most of them eventually ;) [PreviousTruthy](https://basarat.gitbook.io/typescript/recap/truthy) [NextClasses](https://basarat.gitbook.io/typescript/future-javascript/classes) Last updated 5 years ago --- # Rest Parameters | TypeScript Deep Dive Rest parameters (denoted by `...argumentName` for the last argument) allow you to quickly accept multiple arguments in your function and get them as an array. This is demonstrated in the below example. Copy function iTakeItAll(first, second, ...allOthers) { console.log(allOthers); } iTakeItAll('foo', 'bar'); // [] iTakeItAll('foo', 'bar', 'bas', 'qux'); // ['bas','qux'] Rest parameters can be used in any function be it `function`/`()=>`/`class member`. [PreviousArrow Functions](https://basarat.gitbook.io/typescript/future-javascript/arrow-functions) [Nextlet](https://basarat.gitbook.io/typescript/future-javascript/let) Last updated 5 years ago --- # Classes Emit | TypeScript Deep Dive ### [](https://basarat.gitbook.io/typescript/future-javascript/classes/classes-emit#whats-up-with-the-iife) What's up with the IIFE The js generated for the class could have been: Copy function Point(x, y) { this.x = x; this.y = y; } Point.prototype.add = function (point) { return new Point(this.x + point.x, this.y + point.y); }; The reason it's wrapped in an Immediately-Invoked Function Expression (IIFE) i.e. Copy (function () { // BODY return Point; })(); has to do with inheritance. It allows TypeScript to capture the base class as a variable `_super` e.g. Copy var Point3D = (function (_super) { __extends(Point3D, _super); function Point3D(x, y, z) { _super.call(this, x, y); this.z = z; } Point3D.prototype.add = function (point) { var point2D = _super.prototype.add.call(this, point); return new Point3D(point2D.x, point2D.y, this.z + point.z); }; return Point3D; })(Point); Notice that the IIFE allows TypeScript to easily capture the base class `Point` in a `_super` variable and that is used consistently in the class body. [](https://basarat.gitbook.io/typescript/future-javascript/classes/classes-emit#extends) `__extends` --------------------------------------------------------------------------------------------------------- You will notice that as soon as you inherit a class TypeScript also generates the following function: Here `d` refers to the derived class and `b` refers to the base class. This function does two things: 1. copies the static members of the base class onto the child class i.e. `for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];` 2. sets up the child class function's prototype to optionally lookup members on the parent's `proto` i.e. effectively `d.prototype.__proto__ = b.prototype` People rarely have trouble understanding 1, but many people struggle with 2. So an explanation is in order. ### [](https://basarat.gitbook.io/typescript/future-javascript/classes/classes-emit#d.prototype.__proto__-b.prototype) `d.prototype.__proto__ = b.prototype` After having tutored many people about this I find the following explanation to be simplest. First we will explain how the code from `__extends` is equivalent to the simple `d.prototype.__proto__ = b.prototype`, and then why this line in itself is significant. To understand all this you need to know these things: 1. `__proto__` 2. `prototype` 3. effect of `new` on `this` inside the called function 4. effect of `new` on `prototype` and `__proto__` All objects in JavaScript contain a `__proto__` member. This member is often not accessible in older browsers (sometimes documentation refers to this magical property as `[[prototype]]`). It has one objective: If a property is not found on an object during lookup (e.g. `obj.property`) then it is looked up at `obj.__proto__.property`. If it is still not found then `obj.__proto__.__proto__.property` till either: _it is found_ or _the latest_ `_.__proto___` _itself is null_. This explains why JavaScript is said to support _prototypal inheritance_ out of the box. This is shown in the following example, which you can run in the chrome console or Node.js: Cool so you understand `__proto__`. Another useful fact is that all `function`s in JavaScript have a property called `prototype` and that it has a member `constructor` pointing back to the function. This is shown below: Now let's look at _effect of_ `_new_` _on_ `_this_` _inside the called function_. Basically `this` inside the called function is going to point to the newly created object that will be returned from the function. It's simple to see if you mutate a property on `this` inside the function: Now the only other thing you need to know is that calling `new` on a function assigns the `prototype` of the function to the `__proto__` of the newly created object that is returned from the function call. Here is the code you can run to completely understand it: That's it. Now look at the following straight out of `__extends`. I've taken the liberty to number these lines: Reading this function in reverse the `d.prototype = new __()` on line 3 effectively means `d.prototype = {__proto__ : __.prototype}` (because of the effect of `new` on `prototype` and `__proto__`), combining it with the previous line (i.e. line 2 `__.prototype = b.prototype;`) you get `d.prototype = {__proto__ : b.prototype}`. But wait, we wanted `d.prototype.__proto__` i.e. just the proto changed and maintain the old `d.prototype.constructor`. This is where the significance of the first line (i.e. `function __() { this.constructor = d; }`) comes in. Here we will effectively have `d.prototype = {__proto__ : __.prototype, constructor : d}` (because of the effect of `new` on `this` inside the called function). So, since we restore `d.prototype.constructor`, the only thing we have truly mutated is the `__proto__` hence `d.prototype.__proto__ = b.prototype`. ### [](https://basarat.gitbook.io/typescript/future-javascript/classes/classes-emit#d.prototype.__proto__-b.prototype-significance) `d.prototype.__proto__ = b.prototype` significance The significance is that it allows you to add member functions to a child class and inherit others from the base class. This is demonstrated by the following simple example: Basically `bird.fly` will be looked up from `bird.__proto__.fly` (remember that `new` makes the `bird.__proto__` point to `Bird.prototype`) and `bird.walk` (an inherited member) will be looked up from `bird.__proto__.__proto__.walk` (as `bird.__proto__ == Bird.prototype` and `bird.__proto__.__proto__` == `Animal.prototype`). [PreviousClasses](https://basarat.gitbook.io/typescript/future-javascript/classes) [NextArrow Functions](https://basarat.gitbook.io/typescript/future-javascript/arrow-functions) Last updated 5 years ago * [What's up with the IIFE](https://basarat.gitbook.io/typescript/future-javascript/classes/classes-emit#whats-up-with-the-iife) * [\_\_extends](https://basarat.gitbook.io/typescript/future-javascript/classes/classes-emit#extends) * [d.prototype.\_\_proto\_\_ = b.prototype](https://basarat.gitbook.io/typescript/future-javascript/classes/classes-emit#d.prototype.__proto__-b.prototype) * [d.prototype.\_\_proto\_\_ = b.prototype significance](https://basarat.gitbook.io/typescript/future-javascript/classes/classes-emit#d.prototype.__proto__-b.prototype-significance) Copy var __extends = this.__extends || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } __.prototype = b.prototype; d.prototype = new __(); }; Copy var foo = {} // setup on foo as well as foo.__proto__ foo.bar = 123; foo.__proto__.bar = 456; console.log(foo.bar); // 123 delete foo.bar; // remove from object console.log(foo.bar); // 456 delete foo.__proto__.bar; // remove from foo.__proto__ console.log(foo.bar); // undefined Copy function Foo() { } console.log(Foo.prototype); // {} i.e. it exists and is not undefined console.log(Foo.prototype.constructor === Foo); // Has a member called `constructor` pointing back to the function Copy function Foo() { this.bar = 123; } // call with the new operator var newFoo = new Foo(); console.log(newFoo.bar); // 123 Copy function Foo() { } var foo = new Foo(); console.log(foo.__proto__ === Foo.prototype); // True! Copy 1 function __() { this.constructor = d; } 2 __.prototype = b.prototype; 3 d.prototype = new __(); Copy function Animal() { } Animal.prototype.walk = function () { console.log('walk') }; function Bird() { } Bird.prototype.__proto__ = Animal.prototype; Bird.prototype.fly = function () { console.log('fly') }; var bird = new Bird(); bird.walk(); bird.fly(); --- # Classes | TypeScript Deep Dive [](https://basarat.gitbook.io/typescript/future-javascript/classes#classes) Classes ---------------------------------------------------------------------------------------- The reason why it's important to have classes in JavaScript as a first class item is that: 1. [Classes offer a useful structural abstraction](https://basarat.gitbook.io/typescript/main-1/classesareuseful) 2. Provides a consistent way for developers to use classes instead of every framework (emberjs,reactjs etc) coming up with their own version. 3. Object Oriented Developers already understand classes. Finally JavaScript developers can _have_ `_class_`. Here we have a basic class called Point: Copy class Point { x: number; y: number; constructor(x: number, y: number) { this.x = x; this.y = y; } add(point: Point) { return new Point(this.x + point.x, this.y + point.y); } } var p1 = new Point(0, 10); var p2 = new Point(10, 20); var p3 = p1.add(p2); // {x:10,y:30} This class generates the following JavaScript on ES5 emit: This is a fairly idiomatic traditional JavaScript class pattern now as a first class language construct. [](https://basarat.gitbook.io/typescript/future-javascript/classes#inheritance) Inheritance ------------------------------------------------------------------------------------------------ Classes in TypeScript (like other languages) support _single_ inheritance using the `extends` keyword as shown below: If you have a constructor in your class then you _must_ call the parent constructor from your constructor (TypeScript will point this out to you). This ensures that the stuff that it needs to set on `this` gets set. Followed by the call to `super` you can add any additional stuff you want to do in your constructor (here we add another member `z`). Note that you override parent member functions easily (here we override `add`) and still use the functionality of the super class in your members (using `super.` syntax). [](https://basarat.gitbook.io/typescript/future-javascript/classes#statics) Statics ---------------------------------------------------------------------------------------- TypeScript classes support `static` properties that are shared by all instances of the class. A natural place to put (and access) them is on the class itself and that is what TypeScript does: You can have static members as well as static functions. [](https://basarat.gitbook.io/typescript/future-javascript/classes#access-modifiers) Access Modifiers ---------------------------------------------------------------------------------------------------------- TypeScript supports access modifiers `public`,`private` and `protected` which determine the accessibility of a `class` member as shown below: accessible on `public` `protected` `private` class yes yes yes class children yes yes no class instances yes no no If an access modifier is not specified it is implicitly `public` as that matches the _convenient_ nature of JavaScript ๐ŸŒน. Note that at runtime (in the generated JS) these have no significance but will give you compile time errors if you use them incorrectly. An example of each is shown below: As always these modifiers work for both member properties and member functions. [](https://basarat.gitbook.io/typescript/future-javascript/classes#abstract) Abstract ------------------------------------------------------------------------------------------ `abstract` can be thought of as an access modifier. We present it separately because opposed to the previously mentioned modifiers it can be on a `class` as well as any member of the class. Having an `abstract` modifier primarily means that such functionality _cannot be directly invoked_ and a child class must provide the functionality. * `abstract` **classes** cannot be directly instantiated. Instead the user must create some `class` that inherits from the `abstract class`. * `abstract` **members** cannot be directly accessed and a child class must provide the functionality. [](https://basarat.gitbook.io/typescript/future-javascript/classes#constructor-is-optional) Constructor is optional ------------------------------------------------------------------------------------------------------------------------ The class does not need to have a constructor. e.g. the following is perfectly fine. [](https://basarat.gitbook.io/typescript/future-javascript/classes#define-using-constructor) Define using constructor -------------------------------------------------------------------------------------------------------------------------- Having a member in a class and initializing it like below: is such a common pattern that TypeScript provides a shorthand where you can prefix the member with an _access modifier_ and it is automatically declared on the class and copied from the constructor. So the previous example can be re-written as (notice `public x:number`): [](https://basarat.gitbook.io/typescript/future-javascript/classes#property-initializer) Property initializer ------------------------------------------------------------------------------------------------------------------ This is a nifty feature supported by TypeScript (from ES7 actually). You can initialize any member of the class outside the class constructor, useful to provide default (notice `members = []`) [PreviousFuture JavaScript Now](https://basarat.gitbook.io/typescript/future-javascript) [NextClasses Emit](https://basarat.gitbook.io/typescript/future-javascript/classes/classes-emit) Last updated 5 years ago * [Classes](https://basarat.gitbook.io/typescript/future-javascript/classes#classes) * [Inheritance](https://basarat.gitbook.io/typescript/future-javascript/classes#inheritance) * [Statics](https://basarat.gitbook.io/typescript/future-javascript/classes#statics) * [Access Modifiers](https://basarat.gitbook.io/typescript/future-javascript/classes#access-modifiers) * [Abstract](https://basarat.gitbook.io/typescript/future-javascript/classes#abstract) * [Constructor is optional](https://basarat.gitbook.io/typescript/future-javascript/classes#constructor-is-optional) * [Define using constructor](https://basarat.gitbook.io/typescript/future-javascript/classes#define-using-constructor) * [Property initializer](https://basarat.gitbook.io/typescript/future-javascript/classes#property-initializer) Copy var Point = (function () { function Point(x, y) { this.x = x; this.y = y; } Point.prototype.add = function (point) { return new Point(this.x + point.x, this.y + point.y); }; return Point; })(); Copy class Point3D extends Point { z: number; constructor(x: number, y: number, z: number) { super(x, y); this.z = z; } add(point: Point3D) { var point2D = super.add(point); return new Point3D(point2D.x, point2D.y, this.z + point.z); } } Copy class Something { static instances = 0; constructor() { Something.instances++; } } var s1 = new Something(); var s2 = new Something(); console.log(Something.instances); // 2 Copy class FooBase { public x: number; private y: number; protected z: number; } // EFFECT ON INSTANCES var foo = new FooBase(); foo.x; // okay foo.y; // ERROR : private foo.z; // ERROR : protected // EFFECT ON CHILD CLASSES class FooChild extends FooBase { constructor() { super(); this.x; // okay this.y; // ERROR: private this.z; // okay } } Copy abstract class FooCommand {} class BarCommand extends FooCommand {} const fooCommand: FooCommand = new FooCommand(); // Cannot create an instance of an abstract class. const barCommand = new BarCommand(); // You can create an instance of a class that inherits from an abstract class. Copy abstract class FooCommand { abstract execute(): string; } class BarErrorCommand extends FooCommand {} // 'BarErrorCommand' needs implement abstract member 'execute'. class BarCommand extends FooCommand { execute() { return `Command Bar executed`; } } const barCommand = new BarCommand(); barCommand.execute(); // Command Bar executed Copy class Foo {} var foo = new Foo(); Copy class Foo { x: number; constructor(x:number) { this.x = x; } } Copy class Foo { constructor(public x:number) { } } Copy class Foo { members = []; // Initialize directly add(x) { this.members.push(x); } } --- # const | TypeScript Deep Dive `const` is a very welcomed addition offered by ES6 / TypeScript. It allows you to be immutable with variables. This is good from a documentation as well as a runtime perspective. To use const just replace `var` with `const`: Copy const foo = 123; > The syntax is much better (IMHO) than other languages that force the user to type something like `let constant foo` i.e. a variable + behavior specifier. `const` is a good practice for both readability and maintainability and avoids using _magic literals_ e.g. Copy // Low readability if (x > 10) { } // Better! const maxRows = 10; if (x > maxRows) { } [](https://basarat.gitbook.io/typescript/future-javascript/const#const-declarations-must-be-initialized) const declarations must be initialized ---------------------------------------------------------------------------------------------------------------------------------------------------- The following is a compiler error: Copy const foo; // ERROR: const declarations must be initialized [](https://basarat.gitbook.io/typescript/future-javascript/const#left-hand-side-of-assignment-cannot-be-a-constant) Left hand side of assignment cannot be a constant -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Constants are immutable after creation, so if you try to assign them to a new value it is a compiler error: [](https://basarat.gitbook.io/typescript/future-javascript/const#block-scoped) Block Scoped ------------------------------------------------------------------------------------------------ A `const` is block scoped like we saw with [`let`](https://basarat.gitbook.io/typescript/future-javascript/let) : [](https://basarat.gitbook.io/typescript/future-javascript/const#deep-immutability) Deep immutability ---------------------------------------------------------------------------------------------------------- A `const` works with object literals as well, as far as protecting the variable _reference_ is concerned: However, it still allows sub properties of objects to be mutated, as shown below: [](https://basarat.gitbook.io/typescript/future-javascript/const#prefer-const) Prefer const ------------------------------------------------------------------------------------------------ Always use `const`, unless you plan to either lazily initialization of a variable, or do a reassignment (use `let` for those cases). [Previouslet](https://basarat.gitbook.io/typescript/future-javascript/let) [NextDestructuring](https://basarat.gitbook.io/typescript/future-javascript/destructuring) Last updated 5 years ago * [const declarations must be initialized](https://basarat.gitbook.io/typescript/future-javascript/const#const-declarations-must-be-initialized) * [Left hand side of assignment cannot be a constant](https://basarat.gitbook.io/typescript/future-javascript/const#left-hand-side-of-assignment-cannot-be-a-constant) * [Block Scoped](https://basarat.gitbook.io/typescript/future-javascript/const#block-scoped) * [Deep immutability](https://basarat.gitbook.io/typescript/future-javascript/const#deep-immutability) * [Prefer const](https://basarat.gitbook.io/typescript/future-javascript/const#prefer-const) Copy const foo = 123; foo = 456; // ERROR: Left-hand side of an assignment expression cannot be a constant Copy const foo = 123; if (true) { const foo = 456; // Allowed as its a new variable limited to this `if` block } Copy const foo = { bar: 123 }; foo = { bar: 456 }; // ERROR : Left hand side of an assignment expression cannot be a constant Copy const foo = { bar: 123 }; foo.bar = 456; // Allowed! console.log(foo); // { bar: 456 } --- # Arrow Functions | TypeScript Deep Dive * [Arrow Functions](https://basarat.gitbook.io/typescript/future-javascript/arrow-functions#arrow-functions) * [Tip: Arrow Function Need](https://basarat.gitbook.io/typescript/future-javascript/arrow-functions#tip-arrow-function-need) * [Tip: Arrow Function Danger](https://basarat.gitbook.io/typescript/future-javascript/arrow-functions#tip-arrow-function-danger) * [Tip: Libraries that use `this`](https://basarat.gitbook.io/typescript/future-javascript/arrow-functions#tip-arrow-functions-with-libraries-that-use-this) * [Tip: Arrow Function inheritance](https://basarat.gitbook.io/typescript/future-javascript/arrow-functions#tip-arrow-functions-and-inheritance) * [Tip: Quick object return](https://basarat.gitbook.io/typescript/future-javascript/arrow-functions#tip-quick-object-return) [](https://basarat.gitbook.io/typescript/future-javascript/arrow-functions#arrow-functions) Arrow Functions ---------------------------------------------------------------------------------------------------------------- Lovingly called the _fat arrow_ (because `->` is a thin arrow and `=>` is a fat arrow) and also called a _lambda function_ (because of other languages). Another commonly used feature is the fat arrow function `()=>something`. The motivation for a _fat arrow_ is: 1. You don't need to keep typing `function` 2. It lexically captures the meaning of `this` 3. It lexically captures the meaning of `arguments` For a language that claims to be functional, in JavaScript you tend to be typing `function` quite a lot. The fat arrow makes it simple for you to create a function Copy var inc = (x)=>x+1; `this` has traditionally been a pain point in JavaScript. As a wise man once said "I hate JavaScript as it tends to lose the meaning of `this` all too easily". Fat arrows fix it by capturing the meaning of `this` from the surrounding context. Consider this pure JavaScript class: Copy function Person(age) { this.age = age; this.growOld = function() { this.age++; } } var person = new Person(1); setTimeout(person.growOld,1000); setTimeout(function() { console.log(person.age); },2000); // 1, should have been 2 If you run this code in the browser `this` within the function is going to point to `window` because `window` is going to be what executes the `growOld` function. Fix is to use an arrow function: The reason why this works is the reference to `this` is captured by the arrow function from outside the function body. This is equivalent to the following JavaScript code (which is what you would write yourself if you didn't have TypeScript): Note that since you are using TypeScript you can be even sweeter in syntax and combine arrows with classes: > [A sweet video about this pattern ๐ŸŒน](https://egghead.io/lessons/typescript-make-usages-of-this-safe-in-class-methods) ### [](https://basarat.gitbook.io/typescript/future-javascript/arrow-functions#tip-arrow-function-need) Tip: Arrow Function Need Beyond the terse syntax, you only _need_ to use the fat arrow if you are going to give the function to someone else to call. Effectively: If you are going to call it yourself, i.e. then `this` is going to be the correct calling context (in this example `person`). ### [](https://basarat.gitbook.io/typescript/future-javascript/arrow-functions#tip-arrow-function-danger) Tip: Arrow Function Danger In fact if you want `this` _to be the calling context_ you should _not use the arrow function_. This is the case with callbacks used by libraries like jquery, underscore, mocha and others. If the documentation mentions functions on `this` then you should probably just use a `function` instead of a fat arrow. Similarly if you plan to use `arguments` don't use an arrow function. ### [](https://basarat.gitbook.io/typescript/future-javascript/arrow-functions#tip-arrow-functions-with-libraries-that-use-this) Tip: Arrow functions with libraries that use `this` Many libraries do this e.g. `jQuery` iterables (one example [https://api.jquery.com/jquery.each/](https://api.jquery.com/jquery.each/) ) will use `this` to pass you the object that it is currently iterating over. In this case if you want to access the library passed `this` as well as the surrounding context just use a temp variable like `_self` like you would in the absence of arrow functions. ### [](https://basarat.gitbook.io/typescript/future-javascript/arrow-functions#tip-arrow-functions-and-inheritance) Tip: Arrow functions and inheritance Arrow functions as properties on classes work fine with inheritance: However, they do not work with the `super` keyword when you try to override the function in a child class. Properties go on `this`. Since there is only one `this` such functions cannot participate in a call to `super` (`super` only works on prototype members). You can easily get around it by creating a copy of the method before overriding it in the child. [](https://basarat.gitbook.io/typescript/future-javascript/arrow-functions#tip-quick-object-return) Tip: Quick object return --------------------------------------------------------------------------------------------------------------------------------- Sometimes you need a function that just returns a simple object literal. However, something like is parsed as a _block_ containing a _JavaScript Label_ by JavaScript runtimes (cause of the JavaScript specification). > If that doesn't make sense, don't worry, as you get a nice compiler error from TypeScript saying "unused label" anyways. Labels are an old (and mostly unused) JavaScript feature that you can ignore as a modern GOTO (considered bad by experienced developers ๐ŸŒน) You can fix it by surrounding the object literal with `()`: [PreviousClasses Emit](https://basarat.gitbook.io/typescript/future-javascript/classes/classes-emit) [NextRest Parameters](https://basarat.gitbook.io/typescript/future-javascript/rest-parameters) Last updated 5 years ago * [Arrow Functions](https://basarat.gitbook.io/typescript/future-javascript/arrow-functions#arrow-functions) * [Tip: Arrow Function Need](https://basarat.gitbook.io/typescript/future-javascript/arrow-functions#tip-arrow-function-need) * [Tip: Arrow Function Danger](https://basarat.gitbook.io/typescript/future-javascript/arrow-functions#tip-arrow-function-danger) * [Tip: Arrow functions with libraries that use this](https://basarat.gitbook.io/typescript/future-javascript/arrow-functions#tip-arrow-functions-with-libraries-that-use-this) * [Tip: Arrow functions and inheritance](https://basarat.gitbook.io/typescript/future-javascript/arrow-functions#tip-arrow-functions-and-inheritance) * [Tip: Quick object return](https://basarat.gitbook.io/typescript/future-javascript/arrow-functions#tip-quick-object-return) Copy function Person(age) { this.age = age; this.growOld = () => { this.age++; } } var person = new Person(1); setTimeout(person.growOld,1000); setTimeout(function() { console.log(person.age); },2000); // 2 Copy function Person(age) { this.age = age; var _this = this; // capture this this.growOld = function() { _this.age++; // use the captured this } } var person = new Person(1); setTimeout(person.growOld,1000); setTimeout(function() { console.log(person.age); },2000); // 2 Copy class Person { constructor(public age:number) {} growOld = () => { this.age++; } } var person = new Person(1); setTimeout(person.growOld,1000); setTimeout(function() { console.log(person.age); },2000); // 2 Copy var growOld = person.growOld; // Then later someone else calls it: growOld(); Copy person.growOld(); Copy let _self = this; something.each(function() { console.log(_self); // the lexically scoped value console.log(this); // the library passed value }); Copy class Adder { constructor(public a: number) {} add = (b: number): number => { return this.a + b; } } class Child extends Adder { callAdd(b: number) { return this.add(b); } } // Demo to show it works const child = new Child(123); console.log(child.callAdd(123)); // 246 Copy class Adder { constructor(public a: number) {} // This function is now safe to pass around add = (b: number): number => { return this.a + b; } } class ExtendedAdder extends Adder { // Create a copy of parent before creating our own private superAdd = this.add; // Now create our override add = (b: number): number => { return this.superAdd(b); } } Copy // WRONG WAY TO DO IT var foo = () => { bar: 123 }; Copy // Correct ๐ŸŒน var foo = () => ({ bar: 123 }); --- # let | TypeScript Deep Dive `var` Variables in JavaScript are _function scoped_. This is different from many other languages (C# / Java etc.) where the variables are _block scoped_. If you bring a _block scoped_ mindset to JavaScript, you would expect the following to print `123`, instead it will print `456`: Copy var foo = 123; if (true) { var foo = 456; } console.log(foo); // 456 This is because `{` does not create a new _variable scope_. The variable `foo` is the same inside the if _block_ as it is outside the if block. This is a common source of errors in JavaScript programming. This is why TypeScript (and ES6) introduces the `let` keyword to allow you to define variables with true _block scope_. That is if you use `let` instead of `var` you get a true unique element disconnected from what you might have defined outside the scope. The same example is demonstrated with `let`: Copy let foo = 123; if (true) { let foo = 456; } console.log(foo); // 123 Another place where `let` would save you from errors is loops. Copy var index = 0; var array = [1, 2, 3]; for (let index = 0; index < array.length; index++) { console.log(array[index]); } console.log(index); // 0 In all sincerity we find it better to use `let` whenever possible as it leads to fewer surprises for new and existing multi-lingual developers. [](https://basarat.gitbook.io/typescript/future-javascript/let#functions-create-a-new-scope) Functions create a new scope ------------------------------------------------------------------------------------------------------------------------------ Since we mentioned it, we'd like to demonstrate that functions create a new variable scope in JavaScript. Consider the following: This behaves as you would expect. Without this it would be very difficult to write code in JavaScript. [](https://basarat.gitbook.io/typescript/future-javascript/let#generated-js) Generated JS ---------------------------------------------------------------------------------------------- The JS generated by TypeScript is simple renaming of the `let` variable if a similar name already exists in the surrounding scope. E.g. the following is generated as is with a simple replacement of `let` with `var`: However, if the variable name is already taken by the surrounding scope then a new variable name is generated as shown (notice `foo_1`): [](https://basarat.gitbook.io/typescript/future-javascript/let#switch) Switch ---------------------------------------------------------------------------------- You can wrap your `case` bodies in `{}` to reuse variable names reliably in different `case` statement as shown below: [](https://basarat.gitbook.io/typescript/future-javascript/let#let-in-closures) let in closures ---------------------------------------------------------------------------------------------------- A common programming interview question for a JavaScript developer is what is the log of this simple file: One would have expected it to be `0,1,2`. Surprisingly it is going to be `3` for all three functions. Reason is that all three functions are using the variable `i` from the outer scope and at the time we execute them (in the second loop) the value of `i` will be `3` (that's the termination condition for the first loop). A fix would be to create a new variable in each loop specific to that loop iteration. As we've learnt before we can create a new variable scope by creating a new function and immediately executing it (i.e. the IIFE pattern from classes `(function() { /* body */ })();`) as shown below: Here the functions close over (hence called a `closure`) the _local_ variable (conveniently named `local`) and use that instead of the loop variable `i`. > Note that closures come with a performance impact (they need to store the surrounding state). The ES6 `let` keyword in a loop would have the same behavior as the previous example: Using a `let` instead of `var` creates a variable `i` unique to each loop iteration. [](https://basarat.gitbook.io/typescript/future-javascript/let#summary) Summary ------------------------------------------------------------------------------------ `let` is extremely useful to have for the vast majority of code. It can greatly enhance your code readability and decrease the chance of a programming error. [PreviousRest Parameters](https://basarat.gitbook.io/typescript/future-javascript/rest-parameters) [Nextconst](https://basarat.gitbook.io/typescript/future-javascript/const) Last updated 5 years ago * [Functions create a new scope](https://basarat.gitbook.io/typescript/future-javascript/let#functions-create-a-new-scope) * [Generated JS](https://basarat.gitbook.io/typescript/future-javascript/let#generated-js) * [Switch](https://basarat.gitbook.io/typescript/future-javascript/let#switch) * [let in closures](https://basarat.gitbook.io/typescript/future-javascript/let#let-in-closures) * [Summary](https://basarat.gitbook.io/typescript/future-javascript/let#summary) Copy var foo = 123; function test() { var foo = 456; } test(); console.log(foo); // 123 Copy if (true) { let foo = 123; } // becomes // if (true) { var foo = 123; } Copy var foo = '123'; if (true) { let foo = 123; } // becomes // var foo = '123'; if (true) { var foo_1 = 123; // Renamed } Copy switch (name) { case 'x': { let x = 5; // ... break; } case 'y': { let x = 10; // ... break; } } Copy var funcs = []; // create a bunch of functions for (var i = 0; i < 3; i++) { funcs.push(function() { console.log(i); }) } // call them for (var j = 0; j < 3; j++) { funcs[j](); } Copy var funcs = []; // create a bunch of functions for (var i = 0; i < 3; i++) { (function() { var local = i; funcs.push(function() { console.log(local); }) })(); } // call them for (var j = 0; j < 3; j++) { funcs[j](); } Copy var funcs = []; // create a bunch of functions for (let i = 0; i < 3; i++) { // Note the use of let funcs.push(function() { console.log(i); }) } // call them for (var j = 0; j < 3; j++) { funcs[j](); } --- # Destructuring | TypeScript Deep Dive TypeScript supports the following forms of Destructuring (literally named after de-structuring i.e. breaking up the structure): 1. Object Destructuring 2. Array Destructuring It is easy to think of destructuring as an inverse of _structuring_. The method of _structuring_ in JavaScript is the object literal: Copy var foo = { bar: { bas: 123 } }; Without the awesome _structuring_ support built into JavaScript, creating new objects on the fly would indeed be very cumbersome. Destructuring brings the same level of convenience to getting data out of a structure. [](https://basarat.gitbook.io/typescript/future-javascript/destructuring#object-destructuring) Object Destructuring ------------------------------------------------------------------------------------------------------------------------ Destructuring is useful because it allows you to do in a single line, what would otherwise require multiple lines. Consider the following case: Copy var rect = { x: 0, y: 10, width: 15, height: 20 }; // Destructuring assignment var {x, y, width, height} = rect; console.log(x, y, width, height); // 0,10,15,20 rect.x = 10; ({x, y, width, height} = rect); // assign to existing variables using outer parentheses console.log(x, y, width, height); // 10,10,15,20 Here in the absence of destructuring you would have to pick off `x,y,width,height` one by one from `rect`. To assign an extracted variable to a new variable name you can do the following: Additionally you can get _deep_ data out of a structure using destructuring. This is shown in the following example: [](https://basarat.gitbook.io/typescript/future-javascript/destructuring#object-destructuring-with-rest) Object Destructuring with rest -------------------------------------------------------------------------------------------------------------------------------------------- You can pick up any number of elements from an object and get _an object_ of the remaining elements using object destructuring with rest. A common use case is also to ignore certain properties. For example: [](https://basarat.gitbook.io/typescript/future-javascript/destructuring#array-destructuring) Array Destructuring ---------------------------------------------------------------------------------------------------------------------- A common programming question: "How to swap two variables without using a third one?". The TypeScript solution: Note that array destructuring is effectively the compiler doing the `[0], [1], ...` and so on for you. There is no guarantee that these values will exist. [](https://basarat.gitbook.io/typescript/future-javascript/destructuring#array-destructuring-with-rest) Array Destructuring with rest ------------------------------------------------------------------------------------------------------------------------------------------ You can pick up any number of elements from an array and get _an array_ of the remaining elements using array destructuring with rest. [](https://basarat.gitbook.io/typescript/future-javascript/destructuring#array-destructuring-with-ignores) Array Destructuring with ignores ------------------------------------------------------------------------------------------------------------------------------------------------ You can ignore any index by simply leaving its location empty i.e. `, ,` in the left hand side of the assignment. For example: [](https://basarat.gitbook.io/typescript/future-javascript/destructuring#js-generation) JS Generation ---------------------------------------------------------------------------------------------------------- The JavaScript generation for non ES6 targets simply involves creating temporary variables, just like you would have to do yourself without native language support for destructuring e.g. [](https://basarat.gitbook.io/typescript/future-javascript/destructuring#summary) Summary ---------------------------------------------------------------------------------------------- Destructuring can make your code more readable and maintainable by reducing the line count and making the intent clear. Array destructuring can allow you to use arrays as though they were tuples. [Previousconst](https://basarat.gitbook.io/typescript/future-javascript/const) [NextSpread Operator](https://basarat.gitbook.io/typescript/future-javascript/spread-operator) Last updated 5 years ago * [Object Destructuring](https://basarat.gitbook.io/typescript/future-javascript/destructuring#object-destructuring) * [Object Destructuring with rest](https://basarat.gitbook.io/typescript/future-javascript/destructuring#object-destructuring-with-rest) * [Array Destructuring](https://basarat.gitbook.io/typescript/future-javascript/destructuring#array-destructuring) * [Array Destructuring with rest](https://basarat.gitbook.io/typescript/future-javascript/destructuring#array-destructuring-with-rest) * [Array Destructuring with ignores](https://basarat.gitbook.io/typescript/future-javascript/destructuring#array-destructuring-with-ignores) * [JS Generation](https://basarat.gitbook.io/typescript/future-javascript/destructuring#js-generation) * [Summary](https://basarat.gitbook.io/typescript/future-javascript/destructuring#summary) Copy // structure const obj = {"some property": "some value"}; // destructure const {"some property": someProperty} = obj; console.log(someProperty === "some value"); // true Copy var foo = { bar: { bas: 123 } }; var {bar: {bas}} = foo; // Effectively `var bas = foo.bar.bas;` Copy var {w, x, ...remaining} = {w: 1, x: 2, y: 3, z: 4}; console.log(w, x, remaining); // 1, 2, {y:3,z:4} Copy // Example function function goto(point2D: {x: number, y: number}) { // Imagine some code that might break // if you pass in an object // with more items than desired } // Some point you get from somewhere const point3D = {x: 1, y: 2, z: 3}; /** A nifty use of rest to remove extra properties */ const { z, ...point2D } = point3D; goto(point2D); Copy var x = 1, y = 2; [x, y] = [y, x]; console.log(x, y); // 2,1 Copy var [x, y, ...remaining] = [1, 2, 3, 4]; console.log(x, y, remaining); // 1, 2, [3,4] Copy var [x, , ...remaining] = [1, 2, 3, 4]; console.log(x, remaining); // 1, [3,4] Copy var x = 1, y = 2; [x, y] = [y, x]; console.log(x, y); // 2,1 // becomes // var x = 1, y = 2; _a = [y,x], x = _a[0], y = _a[1]; console.log(x, y); var _a; --- # for...of | TypeScript Deep Dive A common error experienced by beginning JavaScript developers is that `for...in` for an array does not iterate over the array items. Instead it iterates over the _keys_ of the object passed in. This is demonstrated in the below example. Here you would expect `9,2,5` but you get the indexes `0,1,2`: Copy var someArray = [9, 2, 5]; for (var item in someArray) { console.log(item); // 0,1,2 } This is one of the reasons why `for...of` exists in TypeScript (and ES6). The following iterates over the array correctly logging out the members as expected: Copy var someArray = [9, 2, 5]; for (var item of someArray) { console.log(item); // 9,2,5 } Similarly TypeScript has no trouble going through a string character by character using `for...of`: Copy var hello = "is it me you're looking for?"; for (var char of hello) { console.log(char); // is it me you're looking for? } [](https://basarat.gitbook.io/typescript/future-javascript/for...of#js-generation) JS Generation ----------------------------------------------------------------------------------------------------- For pre ES6 targets TypeScript will generate the standard `for (var i = 0; i < list.length; i++)` kind of loop. For example here's what gets generated for our previous example: Copy var someArray = [9, 2, 5]; for (var item of someArray) { console.log(item); } // becomes // for (var _i = 0; _i < someArray.length; _i++) { var item = someArray[_i]; console.log(item); } You can see that using `for...of` makes _intent_ clearer and also decreases the amount of code you have to write (and variable names you need to come up with). [](https://basarat.gitbook.io/typescript/future-javascript/for...of#limitations) Limitations ------------------------------------------------------------------------------------------------- If you are not targeting ES6 or above, the generated code assumes the property `length` exists on the object and that the object can be indexed via numbers e.g. `obj[2]`. So it is only supported on `string` and `array` for these legacy JS engines. If TypeScript can see that you are not using an array or a string it will give you a clear error _"is not an array type or a string type"_; Use `for...of` only for stuff that _you know_ to be an array or a string. Note that this limitation might be removed in a future version of TypeScript. [](https://basarat.gitbook.io/typescript/future-javascript/for...of#summary) Summary ----------------------------------------------------------------------------------------- You would be surprised at how many times you will be iterating over the elements of an array. The next time you find yourself doing that, give `for...of` a go. You might just make the next person who reviews your code happy. [PreviousSpread Operator](https://basarat.gitbook.io/typescript/future-javascript/spread-operator) [NextIterators](https://basarat.gitbook.io/typescript/future-javascript/iterators) Last updated 5 years ago * [JS Generation](https://basarat.gitbook.io/typescript/future-javascript/for...of#js-generation) * [Limitations](https://basarat.gitbook.io/typescript/future-javascript/for...of#limitations) * [Summary](https://basarat.gitbook.io/typescript/future-javascript/for...of#summary) Copy let articleParagraphs = document.querySelectorAll("article > p"); // Error: Nodelist is not an array type or a string type for (let paragraph of articleParagraphs) { paragraph.classList.add("read"); } --- # Project | TypeScript Deep Dive To create a successful project using TypeScript you need to understand the various project organization language features available. In this section we will cover "compilation context", declaration spaces and modules. [PreviousAsync Await](https://basarat.gitbook.io/typescript/future-javascript/async-await) [NextCompilation Context](https://basarat.gitbook.io/typescript/project/compilation-context) Last updated 5 years ago --- # Spread Operator | TypeScript Deep Dive The main objective of the spread operator is to _spread_ the elements of an array or object. This is best explained with examples. [](https://basarat.gitbook.io/typescript/future-javascript/spread-operator#apply) Apply -------------------------------------------------------------------------------------------- A common use case is to spread an array into the function arguments. Previously you would need to use `Function.prototype.apply`: Copy function foo(x, y, z) { } var args = [0, 1, 2]; foo.apply(null, args); Now you can do this simply by prefixing the arguments with `...` as shown below: Copy function foo(x, y, z) { } var args = [0, 1, 2]; foo(...args); Here we are _spreading_ the `args` array into positional `arguments`. [](https://basarat.gitbook.io/typescript/future-javascript/spread-operator#destructuring) Destructuring ------------------------------------------------------------------------------------------------------------ We've already seen one usage of this in _destructuring_: Copy var [x, y, ...remaining] = [1, 2, 3, 4]; console.log(x, y, remaining); // 1,2,[3,4] The motivation here is to simply make it easy for you to capture the remaining elements of an array when destructuring. [](https://basarat.gitbook.io/typescript/future-javascript/spread-operator#array-assignment) Array Assignment ------------------------------------------------------------------------------------------------------------------ The spread operator allows you to easily place an _expanded version_ of an array into another array. This is demonstrated in the example below: You can put the expanded array in at any position, and get the effect you'd expect: [](https://basarat.gitbook.io/typescript/future-javascript/spread-operator#object-spread) Object spread ------------------------------------------------------------------------------------------------------------ You can also spread an object into another object. A common use case is to simply add a property to an object without mutating the original: For objects, the order of where you put the spread matters. This works something like `Object.assign`, and does what you'd expect: what comes first is 'overridden' by what comes later: Another common use case is a simple shallow extend: [](https://basarat.gitbook.io/typescript/future-javascript/spread-operator#summary) Summary ------------------------------------------------------------------------------------------------ `apply` is something that you often use in JavaScript, so it's good to have a better syntax where you don't have that ugly `null` for the `this` argument. Also having a dedicated syntax for moving arrays out of (destructuring) or into (assignment) other arrays provides a neat syntax for when you are doing array processing on partial arrays. [PreviousDestructuring](https://basarat.gitbook.io/typescript/future-javascript/destructuring) [Nextfor...of](https://basarat.gitbook.io/typescript/future-javascript/for...of) Last updated 5 years ago * [Apply](https://basarat.gitbook.io/typescript/future-javascript/spread-operator#apply) * [Destructuring](https://basarat.gitbook.io/typescript/future-javascript/spread-operator#destructuring) * [Array Assignment](https://basarat.gitbook.io/typescript/future-javascript/spread-operator#array-assignment) * [Object spread](https://basarat.gitbook.io/typescript/future-javascript/spread-operator#object-spread) * [Summary](https://basarat.gitbook.io/typescript/future-javascript/spread-operator#summary) Copy var list = [1, 2]; list = [...list, 3, 4]; console.log(list); // [1,2,3,4] Copy var list = [1, 2]; list = [0, ...list, 4]; console.log(list); // [0,1,2,4] Copy const point2D = {x: 1, y: 2}; /** Create a new object by using all the point2D props along with z */ const point3D = {...point2D, z: 3}; Copy const point2D = {x: 1, y: 2}; const anotherPoint3D = {x: 5, z: 4, ...point2D}; console.log(anotherPoint3D); // {x: 1, y: 2, z: 4} const yetAnotherPoint3D = {...point2D, x: 5, z: 4} console.log(yetAnotherPoint3D); // {x: 5, y: 2, z: 4} Copy const foo = {a: 1, b: 2, c: 0}; const bar = {c: 1, d: 2}; /** Merge foo and bar */ const fooBar = {...foo, ...bar}; // fooBar is now {a: 1, b: 2, c: 1, d: 2} --- # Template Strings | TypeScript Deep Dive Syntactically these are strings that use backticks ( i.e. \` ) instead of single (') or double (") quotes. The motivation of Template Literals is three fold: * String Interpolation * Multiline Strings * Tagged Templates [](https://basarat.gitbook.io/typescript/future-javascript/template-strings#string-interpolation) String Interpolation --------------------------------------------------------------------------------------------------------------------------- Another common use case is when you want to generate some string out of some static strings + some variables. For this you would need some _templating logic_ and this is where _template strings_ originally got their name from. They have since been officially renamed to _template literals_. Here's how you would potentially generate an html string previously: Copy var lyrics = 'Never gonna give you up'; var html = '
' + lyrics + '
'; Now with template literals you can just do: Copy var lyrics = 'Never gonna give you up'; var html = `
${lyrics}
`; Note that any placeholder inside the interpolation (`${` and `}`) is treated as a JavaScript expression and evaluated as such e.g. you can do fancy math. Copy console.log(`1 and 1 make ${1 + 1}`); [](https://basarat.gitbook.io/typescript/future-javascript/template-strings#multiline-literals) Multiline Literals ----------------------------------------------------------------------------------------------------------------------- Ever wanted to put a newline in a JavaScript string? Perhaps you wanted to embed some lyrics? You would have needed to _escape the literal newline_ using our favorite escape character `\`, and then put a new line into the string manually `\n` at the next line. This is shown below: Copy var lyrics = "Never gonna give you up \ \nNever gonna let you down"; With TypeScript you can just use a template string: [](https://basarat.gitbook.io/typescript/future-javascript/template-strings#tagged-templates) Tagged Templates ------------------------------------------------------------------------------------------------------------------- You can place a function (called a `tag`) before the template string and it gets the opportunity to pre process the template string literals plus the values of all the placeholder expressions and return a result. A few notes: * All the static literals are passed in as an array for the first argument. * All the values of the placeholders expressions are passed in as the remaining arguments. Most commonly you would just use rest parameters to convert these into an array as well. Here is an example where we have a tag function (named `htmlEscape`) that escapes the html from all the placeholders: > Note: You can annotate `placeholders` to be any `[]`. Whatever you annotate it as, TypeScript will type check to make sure the placeholders used to call the tag match the annotation. For example if you expect to deal with `string` or `number`s you can annotate `...placeholders:(string | number)[]` [](https://basarat.gitbook.io/typescript/future-javascript/template-strings#generated-js) Generated JS ----------------------------------------------------------------------------------------------------------- For pre ES6 compile targets the code is fairly simple. Multiline strings become escaped strings. String interpolation becomes _string concatenation_. Tagged Templates become function calls. [](https://basarat.gitbook.io/typescript/future-javascript/template-strings#summary) Summary ------------------------------------------------------------------------------------------------- Multiline strings and string interpolation are just great things to have in any language. It's great that you can now use them in your JavaScript (thanks TypeScript!). Tagged templates allow you to create powerful string utilities. [PreviousIterators](https://basarat.gitbook.io/typescript/future-javascript/iterators) [NextPromise](https://basarat.gitbook.io/typescript/future-javascript/promise) Last updated 5 years ago * [String Interpolation](https://basarat.gitbook.io/typescript/future-javascript/template-strings#string-interpolation) * [Multiline Literals](https://basarat.gitbook.io/typescript/future-javascript/template-strings#multiline-literals) * [Tagged Templates](https://basarat.gitbook.io/typescript/future-javascript/template-strings#tagged-templates) * [Generated JS](https://basarat.gitbook.io/typescript/future-javascript/template-strings#generated-js) * [Summary](https://basarat.gitbook.io/typescript/future-javascript/template-strings#summary) Copy var lyrics = `Never gonna give you up Never gonna let you down`; Copy var say = "a bird in hand > two in the bush"; var html = htmlEscape `
I would just like to say : ${say}
`; // a sample tag function function htmlEscape(literals: TemplateStringsArray, ...placeholders: string[]) { let result = ""; // interleave the literals with the placeholders for (let i = 0; i < placeholders.length; i++) { result += literals[i]; result += placeholders[i] .replace(/&/g, '&') .replace(/"/g, '"') .replace(/'/g, ''') .replace(//g, '>'); } // add the last literal result += literals[literals.length - 1]; return result; } --- # Async Await | TypeScript Deep Dive > [A PRO egghead video course that covers the same material](https://egghead.io/courses/async-await-using-typescript) As a thought experiment imagine the following: a way to tell the JavaScript runtime to pause the executing of code on the `await` keyword when used on a promise and resume _only_ once (and if) the promise returned from the function is settled: Copy // Not actual code. A thought experiment async function foo() { try { var val = await getMeAPromise(); console.log(val); } catch(err) { console.log('Error: ', err.message); } } When the promise settles execution continues, * if it was fulfilled then await will return the value, * if it's rejected an error will be thrown synchronously which we can catch. This suddenly (and magically) makes asynchronous programming as easy as synchronous programming. Three things needed for this thought experiment are: * Ability to _pause function_ execution. * Ability to _put a value inside_ the function. * Ability to _throw an exception inside_ the function. This is exactly what generators allowed us to do! The thought experiment _is actually real_ and so is the `async`/`await` implementation in TypeScript / JavaScript. Under the covers it just uses generators. [](https://basarat.gitbook.io/typescript/future-javascript/async-await#generated-javascript) Generated JavaScript ---------------------------------------------------------------------------------------------------------------------- You don't have to understand this, but it's fairly simple if you've [read up on generators](https://basarat.gitbook.io/typescript/future-javascript/generators) . The function `foo` can be simply wrapped up as follows: where the `wrapToReturnPromise` just executes the generator function to get the `generator` and then use `generator.next()`, if the value is a `promise` it would `then`+`catch` the promise and depending upon the result call `generator.next(result)` or `generator.throw(error)`. That's it! [](https://basarat.gitbook.io/typescript/future-javascript/async-await#async-await-support-in-typescript) Async Await Support in TypeScript ------------------------------------------------------------------------------------------------------------------------------------------------ **Async - Await** has been supported by [TypeScript since version 1.7](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-1-7.html) . Asynchronous functions are prefixed with the _async_ keyword; _await_ suspends the execution until an asynchronous function return promise is fulfilled and unwraps the value from the _Promise_ returned. It was only supported for **target es6** transpiling directly to **ES6 generators**. **TypeScript 2.1** [added the capability to ES3 and ES5 run-times](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-1.html) , meaning youโ€™ll be free to take advantage of it no matter what environment youโ€™re using. It's important to notice that we can use async / await with TypeScript 2.1 and many browsers are supported, of course, having globally added a **polyfill for Promise**. Let's see this **example** and take a look at this code to figure out how TypeScript async / await **notation** works: **Transpiling to ES6 (--target es6)** You can see full example [here](https://cdn.rawgit.com/basarat/typescript-book/705e4496/code/async-await/es6/asyncAwaitES6.js) . **Transpiling to ES5 (--target es5)** You can see full example [here](https://cdn.rawgit.com/basarat/typescript-book/705e4496/code/async-await/es5/asyncAwaitES5.js) . **Note**: for both target scenarios, we need to make sure our run-time has an ECMAScript-compliant Promise available globally. That might involve grabbing a polyfill for Promise. We also need to make sure that TypeScript knows Promise exists by setting our lib flag to something like "dom", "es2015" or "dom", "es2015.promise", "es5". **We can see what browsers DO have Promise support (native and polyfilled)** [**here**](https://kangax.github.io/compat-table/es6/#test-Promise) **.** [PreviousGenerators](https://basarat.gitbook.io/typescript/future-javascript/generators) [NextProject](https://basarat.gitbook.io/typescript/project) Last updated 5 years ago * [Generated JavaScript](https://basarat.gitbook.io/typescript/future-javascript/async-await#generated-javascript) * [Async Await Support in TypeScript](https://basarat.gitbook.io/typescript/future-javascript/async-await#async-await-support-in-typescript) Copy const foo = wrapToReturnPromise(function* () { try { var val = yield getMeAPromise(); console.log(val); } catch(err) { console.log('Error: ', err.message); } }); Copy function delay(milliseconds: number, count: number): Promise { return new Promise(resolve => { setTimeout(() => { resolve(count); }, milliseconds); }); } // async function always returns a Promise async function dramaticWelcome(): Promise { console.log("Hello"); for (let i = 0; i < 5; i++) { // await is converting Promise into number const count: number = await delay(500, i); console.log(count); } console.log("World!"); } dramaticWelcome(); Copy var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; function delay(milliseconds, count) { return new Promise(resolve => { setTimeout(() => { resolve(count); }, milliseconds); }); } // async function always returns a Promise function dramaticWelcome() { return __awaiter(this, void 0, void 0, function* () { console.log("Hello"); for (let i = 0; i < 5; i++) { // await is converting Promise into number const count = yield delay(500, i); console.log(count); } console.log("World!"); }); } dramaticWelcome(); Copy var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [0, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; function delay(milliseconds, count) { return new Promise(function (resolve) { setTimeout(function () { resolve(count); }, milliseconds); }); } // async function always returns a Promise function dramaticWelcome() { return __awaiter(this, void 0, void 0, function () { var i, count; return __generator(this, function (_a) { switch (_a.label) { case 0: console.log("Hello"); i = 0; _a.label = 1; case 1: if (!(i < 5)) return [3 /*break*/, 4]; return [4 /*yield*/, delay(500, i)]; case 2: count = _a.sent(); console.log(count); _a.label = 3; case 3: i++; return [3 /*break*/, 1]; case 4: console.log("World!"); return [2 /*return*/]; } }); }); } dramaticWelcome(); --- # Node.js QuickStart | TypeScript Deep Dive TypeScript has had _first class_ support for Node.js since inception. Here's how to setup a quick Node.js project: > Note: many of these steps are actually just common practice Node.js setup steps 1. Setup a Node.js project `package.json`. Quick one : `npm init -y` 2. Add TypeScript (`npm install typescript --save-dev`) 3. Add `node.d.ts` (`npm install @types/node --save-dev`) 4. Init a `tsconfig.json` for TypeScript options with a few key options in your tsconfig.json (`npx tsc --init --rootDir src --outDir lib --esModuleInterop --resolveJsonModule --lib es6,dom --module commonjs`) That's it! Fire up your IDE (e.g. `code .`) and play around. Now you can use all the built in node modules (e.g. `import * as fs from 'fs';`) with all the safety and developer ergonomics of TypeScript! All your TypeScript code goes in `src` and the generated JavaScript goes in `lib`. [](https://basarat.gitbook.io/typescript/nodejs#bonus-live-compile--run) Bonus: Live compile + run ------------------------------------------------------------------------------------------------------- * Add `ts-node` which we will use for live compile + run in node (`npm install ts-node --save-dev`) * Add `nodemon` which will invoke `ts-node` whenever a file is changed (`npm install nodemon --save-dev`) Now just add a `script` target to your `package.json` based on your application entry e.g. assuming its `index.ts`: Copy "scripts": { "start": "npm run build:live", "build": "tsc -p .", "build:live": "nodemon --watch 'src/**/*.ts' --exec \"ts-node\" src/index.ts" }, So you can now run `npm start` and as you edit `index.ts`: * nodemon reruns its command (ts-node) * ts-node transpiles automatically picking up tsconfig.json and the installed TypeScript version, * ts-node runs the output JavaScript through Node.js. And when you are ready to deploy your JavaScript application run `npm run build`. [](https://basarat.gitbook.io/typescript/nodejs#bonus-points) Bonus points ------------------------------------------------------------------------------- Such NPM modules work just fine with browserify (using tsify) or webpack (using ts-loader). [PreviousDynamic Import Expressions](https://basarat.gitbook.io/typescript/project/dynamic-import-expressions) [NextBrowser QuickStart](https://basarat.gitbook.io/typescript/browser) Last updated 5 years ago * [Bonus: Live compile + run](https://basarat.gitbook.io/typescript/nodejs#bonus-live-compile--run) * [Bonus points](https://basarat.gitbook.io/typescript/nodejs#bonus-points) --- # Which Files? | TypeScript Deep Dive Use `include` and `exclude` to specify files / folders / globs. E.g.: Copy { "include":[\ "./folder"\ ], "exclude":[\ "./folder/**/*.spec.ts",\ "./folder/someSubFolder"\ ] } [](https://basarat.gitbook.io/typescript/project/compilation-context/files#globs) Globs -------------------------------------------------------------------------------------------- * For globs : `**/*` (e.g. sample usage `somefolder/**/*`) means all folder and any files (the extensions `.ts`/`.tsx` will be assumed and if `allowJs:true` so will `.js`/`.jsx`) [](https://basarat.gitbook.io/typescript/project/compilation-context/files#files-option) `files` option ------------------------------------------------------------------------------------------------------------ Alternatively, you can use `files` to be explicit: Copy { "files":[\ "./some/file.ts"\ ] } But it is not recommended as you have to keep updating it. Instead use `include` to just add the containing folder. [Previoustsconfig.json](https://basarat.gitbook.io/typescript/project/compilation-context/tsconfig) [NextDeclaration Spaces](https://basarat.gitbook.io/typescript/project/declarationspaces) Last updated 5 years ago * [Globs](https://basarat.gitbook.io/typescript/project/compilation-context/files#globs) * [files option](https://basarat.gitbook.io/typescript/project/compilation-context/files#files-option) --- # Iterators | TypeScript Deep Dive Iterator itself is not a TypeScript or ES6 feature, Iterator is a Behavioral Design Pattern common for Object oriented programming languages. It is, generally, an object which implements the following interface: Copy interface Iterator { next(value?: any): IteratorResult; return?(value?: any): IteratorResult; throw?(e?: any): IteratorResult; } ([More on that `` notation later](https://basarat.gitbook.io/typescript/type-system/generics) ) This interface allows to retrieve a value from some collection or sequence which belongs to the object. The `IteratorResult` is simply a `value`+`done` pair: Copy interface IteratorResult { done: boolean; value: T; } Imagine that there's an object of some frame, which includes the list of components of which this frame consists. With Iterator interface it is possible to retrieve components from this frame object like below: Copy class Component { constructor (public name: string) {} } class Frame implements Iterator { private pointer = 0; constructor(public name: string, public components: Component[]) {} public next(): IteratorResult { if (this.pointer < this.components.length) { return { done: false, value: this.components[this.pointer++] } } else { return { done: true, value: null } } } } let frame = new Frame("Door", [new Component("top"), new Component("bottom"), new Component("left"), new Component("right")]); let iteratorResult1 = frame.next(); //{ done: false, value: Component { name: 'top' } } let iteratorResult2 = frame.next(); //{ done: false, value: Component { name: 'bottom' } } let iteratorResult3 = frame.next(); //{ done: false, value: Component { name: 'left' } } let iteratorResult4 = frame.next(); //{ done: false, value: Component { name: 'right' } } let iteratorResult5 = frame.next(); //{ done: true, value: null } //It is possible to access the value of iterator result via the value property: let component = iteratorResult1.value; //Component { name: 'top' } Again. Iterator itself is not a TypeScript feature, this code could work without implementing Iterator and IteratorResult interfaces explicitly. However, it is very helpful to use these common ES6 [interfaces](https://basarat.gitbook.io/typescript/type-system/interfaces) for code consistency. Ok, Nice, but could be more helpful. ES6 defines the _iterable protocol_ which includes the \[Symbol.iterator\] `symbol` if the Iterable interface is implemented: Unfortunately `frame.next()` won't work with this pattern and it also looks a bit clunky. IterableIterator interface to the rescue! Both `frame.next()` and `for` cycle now work fine with IterableIterator interface. Iterator does not have to iterate a finite value. The typical example is a Fibonacci sequence: [](https://basarat.gitbook.io/typescript/future-javascript/iterators#building-code-with-iterators-for-es5-target) Building code with iterators for ES5 target ------------------------------------------------------------------------------------------------------------------------------------------------------------------ Code examples above require ES6 target. However, it could work with ES5 target as well if target JS engine supports `Symbol.iterator`. This can be achieved by using ES6 lib with ES5 target (add es6.d.ts to your project) to make it compile. Compiled code should work in node 4+, Google Chrome and in some other browsers. [Previousfor...of](https://basarat.gitbook.io/typescript/future-javascript/for...of) [NextTemplate Strings](https://basarat.gitbook.io/typescript/future-javascript/template-strings) Last updated 5 years ago Copy //... class Frame implements Iterable { constructor(public name: string, public components: Component[]) {} [Symbol.iterator]() { let pointer = 0; let components = this.components; return { next(): IteratorResult { if (pointer < components.length) { return { done: false, value: components[pointer++] } } else { return { done: true, value: null } } } } } } let frame = new Frame("Door", [new Component("top"), new Component("bottom"), new Component("left"), new Component("right")]); for (let cmp of frame) { console.log(cmp); } Copy //... class Frame implements IterableIterator { private pointer = 0; constructor(public name: string, public components: Component[]) {} public next(): IteratorResult { if (this.pointer < this.components.length) { return { done: false, value: this.components[this.pointer++] } } else { return { done: true, value: null } } } [Symbol.iterator](): IterableIterator { return this; } } //... Copy class Fib implements IterableIterator { protected fn1 = 0; protected fn2 = 1; constructor(protected maxValue?: number) {} public next(): IteratorResult { var current = this.fn1; this.fn1 = this.fn2; this.fn2 = current + this.fn1; if (this.maxValue != null && current >= this.maxValue) { return { done: true, value: null } } return { done: false, value: current } } [Symbol.iterator](): IterableIterator { return this; } } let fib = new Fib(); fib.next() //{ done: false, value: 0 } fib.next() //{ done: false, value: 1 } fib.next() //{ done: false, value: 1 } fib.next() //{ done: false, value: 2 } fib.next() //{ done: false, value: 3 } fib.next() //{ done: false, value: 5 } let fibMax50 = new Fib(50); console.log(Array.from(fibMax50)); // [ 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 ] let fibMax21 = new Fib(21); for(let num of fibMax21) { console.log(num); //Prints fibonacci sequence 0 to 21 } --- # Library QuickStart | TypeScript Deep Dive * [A lesson on creating TypeScript node modules](https://egghead.io/lessons/typescript-create-high-quality-npm-packages-using-typescript) Using modules written in TypeScript is super fun as you get great compile time safety and autocomplete (essentially executable documentation). TypeScript modules can be consumed both in the nodejs (as is) browser (with something like webpack). Creating a high quality TypeScript module is simple. Assume the following desired folder structure for your package: Copy package โ”œโ”€ package.json โ”œโ”€ tsconfig.json โ”œโ”€ src โ”‚ โ”œโ”€ index.ts โ”‚ โ”œโ”€ foo.ts โ”‚ โ””โ”€ ...All your source files (Authored) โ””โ”€ lib โ”œโ”€ index.d.ts.map โ”œโ”€ index.d.ts โ”œโ”€ index.js โ”œโ”€ foo.d.ts.map โ”œโ”€ foo.d.ts โ”œโ”€ foo.js โ””โ”€ ... All your compiled files (Generated) * `src/index.ts`: Here you would export anything you expect to be consumed from your project. E.g `export { Foo } from './foo';`. Exporting from this file makes it available for consumption when someone does `import { /* Here */ } from 'example';` * In your `tsconfig.json` * have `compilerOptions`: `"outDir": "lib"` + `"declaration": true` + `"declarationMap" : true` < This generates `.js` (JavaScript) `.d.ts` (declarations for TypeSafety) and `.d.ts.map` (enables `declaration .d.ts` => `source .ts` IDE navigation) in the lib folder. * have `include: ["src"]` < This includes all the files from the `src` dir. * In your `package.json` have * `"main": "lib/index"` < This tells to load `lib/index.js` for runtime code. * `"types": "lib/index"` < This tells TypeScript to load `lib/index.d.ts` for type checking. Example package: * `npm install typestyle` [for TypeStyle](https://www.npmjs.com/package/typestyle) * Usage: `import { style } from 'typestyle';` will be completely type safe. [](https://basarat.gitbook.io/typescript/library#managing-dependencies) Managing Dependencies -------------------------------------------------------------------------------------------------- ### [](https://basarat.gitbook.io/typescript/library#devdependencies) devDependencies * If your package depends on another package while you are developing it (e.g. `prettier`) you should install them as a `devDependency`. This way they will not pollute the `node_modules` of your module's consumers (as `npm i foo` does not install `devDependencies` of `foo`). * `typescript` is normally a `devDependency` as you only use it to build your package. The consumers can use your package with or without TypeScript. * If your package depends on other JavaScript authored packages and you want to use it with type safety in your project, put their types (e.g. `@types/foo`) in `devDependencies`. JavaScript types should be managed _out of bound_ from the main NPM streams. The JavaScript ecosystem breaks types without semantic versioning too commonly, so if your users need types for these they should install the `@types/foo` version that works for them. If you want to guide users to install these types you can put them in `peerDependencies` mentioned next. ### [](https://basarat.gitbook.io/typescript/library#peerdependencies) peerDependencies If your package depends on a package that it heavily _works with_ (as opposed to _works using_) e.g. `react`, put them in `peerDependencies` just like you would with raw JS packages. To test them locally you should also put them in `devDependencies`. Now: * When you are developing the package you will get the version of the dependency you specified in your `devDependencies`. * When someone installs your package they will _not_ get this dependency (as `npm i foo` does not install `devDependencies` of `foo`) but they will get a warning that they should install the missing `peerDependencies` of your package. ### [](https://basarat.gitbook.io/typescript/library#dependencies) dependencies If your package _wraps_ another package (meant for internal use even after compilation) you should put them in `dependencies`. Now when someone installs your package they will get your package + any of its dependencies. [PreviousBrowser QuickStart](https://basarat.gitbook.io/typescript/browser) [NextTypeScript's Type System](https://basarat.gitbook.io/typescript/type-system) Last updated 5 years ago * [Managing Dependencies](https://basarat.gitbook.io/typescript/library#managing-dependencies) * [devDependencies](https://basarat.gitbook.io/typescript/library#devdependencies) * [peerDependencies](https://basarat.gitbook.io/typescript/library#peerdependencies) * [dependencies](https://basarat.gitbook.io/typescript/library#dependencies) --- # Modules | TypeScript Deep Dive [](https://basarat.gitbook.io/typescript/project/modules#global-module) Global Module ------------------------------------------------------------------------------------------ By default when you start typing code in a new TypeScript file your code is in a _global_ namespace. As a demo consider a file `foo.ts`: Copy var foo = 123; If you now create a _new_ file `bar.ts` in the same project, you will be _allowed_ by the TypeScript type system to use the variable `foo` as if it was available globally: Copy var bar = foo; // allowed Needless to say having a global namespace is dangerous as it opens your code up for naming conflicts. We recommend using file modules which are presented next. [](https://basarat.gitbook.io/typescript/project/modules#file-module) File Module -------------------------------------------------------------------------------------- Also called _external modules_. If you have an `import` or an `export` at the root level of a TypeScript file then it creates a _local_ scope within that file. So if we were to change the previous `foo.ts` to the following (note the `export` usage): Copy export var foo = 123; We will no longer have `foo` in the global namespace. This can be demonstrated by creating a new file `bar.ts` as follows: Copy var bar = foo; // ERROR: "cannot find name 'foo'" If you want to use stuff from `foo.ts` in `bar.ts` _you need to explicitly import it_. This is shown in an updated `bar.ts` below: Copy import { foo } from "./foo"; var bar = foo; // allowed Using an `import` in `bar.ts` not only allows you to bring in stuff from other files, but also marks the file `bar.ts` as a _module_ and therefore, declarations in `bar.ts` don't pollute the global namespace either. What JavaScript is generated from a given TypeScript file that uses external modules is driven by the compiler flag called `module`. [PreviousDeclaration Spaces](https://basarat.gitbook.io/typescript/project/declarationspaces) [NextFile Module Details](https://basarat.gitbook.io/typescript/project/modules/external-modules) Last updated 5 years ago * [Global Module](https://basarat.gitbook.io/typescript/project/modules#global-module) * [File Module](https://basarat.gitbook.io/typescript/project/modules#file-module) --- # tsconfig.json | TypeScript Deep Dive [](https://basarat.gitbook.io/typescript/project/compilation-context/tsconfig#basic) Basic ----------------------------------------------------------------------------------------------- It is extremely easy to get started with tsconfig.json as the basic file you need is: Copy {} i.e. an empty JSON file at the _root_ of your project. This way TypeScript will include _all_ the `.ts` files in this directory (and sub directories) as a part of the compilation context. It will also select a few sane default compiler options. [](https://basarat.gitbook.io/typescript/project/compilation-context/tsconfig#compileroptions) compilerOptions ------------------------------------------------------------------------------------------------------------------- You can customize the compiler options using `compilerOptions`: Copy { "compilerOptions": { /* Basic Options */ "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'. */ "module": "commonjs", /* Specify module code generation: 'commonjs', 'amd', 'system', 'umd' or 'es2015'. */ "lib": [], /* Specify library files to be included in the compilation: */ "allowJs": true, /* Allow JavaScript files to be compiled. */ "checkJs": true, /* Report errors in .js files. */ "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ "declaration": true, /* Generates corresponding '.d.ts' file. */ "sourceMap": true, /* Generates corresponding '.map' file. */ "outFile": "./", /* Concatenate and emit output to single file. */ "outDir": "./", /* Redirect output structure to the directory. */ "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ "removeComments": true, /* Do not emit comments to output. */ "noEmit": true, /* Do not emit outputs. */ "importHelpers": true, /* Import emit helpers from 'tslib'. */ "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ /* Strict Type-Checking Options */ "strict": true, /* Enable all strict type-checking options. */ "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ "strictNullChecks": true, /* Enable strict null checks. */ "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ /* Additional Checks */ "noUnusedLocals": true, /* Report errors on unused locals. */ "noUnusedParameters": true, /* Report errors on unused parameters. */ "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ /* Module Resolution Options */ "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ "typeRoots": [], /* List of folders to include type definitions from. */ "types": [], /* Type declaration files to be included in compilation. */ "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ /* Source Map Options */ "sourceRoot": "./", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ "mapRoot": "./", /* Specify the location where debugger should locate map files instead of generated locations. */ "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ /* Experimental Options */ "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ "emitDecoratorMetadata": true /* Enables experimental support for emitting type metadata for decorators. */ } } These (and more) compiler options will be discussed later. [](https://basarat.gitbook.io/typescript/project/compilation-context/tsconfig#typescript-compiler) TypeScript compiler --------------------------------------------------------------------------------------------------------------------------- Good IDEs come with built in support for on the fly `ts` to `js` compilation. However, if you want to run the TypeScript compiler manually from the command line when using `tsconfig.json`, you can do it in a few ways: * Just run `tsc` and it will look for `tsconfig.json` in the current as well as all parent folders till it finds it. * Run `tsc -p ./path-to-project-directory`. Of course the path can be absolute or relative to the current directory. You can even start the TypeScript compiler in _watch_ mode using `tsc -w` and it will watch your TypeScript project files for changes. [PreviousCompilation Context](https://basarat.gitbook.io/typescript/project/compilation-context) [NextWhich Files?](https://basarat.gitbook.io/typescript/project/compilation-context/files) Last updated 5 years ago * [Basic](https://basarat.gitbook.io/typescript/project/compilation-context/tsconfig#basic) * [compilerOptions](https://basarat.gitbook.io/typescript/project/compilation-context/tsconfig#compileroptions) * [TypeScript compiler](https://basarat.gitbook.io/typescript/project/compilation-context/tsconfig#typescript-compiler) --- # Browser QuickStart | TypeScript Deep Dive [](https://basarat.gitbook.io/typescript/browser#typescript-in-the-browser) TypeScript in the browser ---------------------------------------------------------------------------------------------------------- [![DesignTSX](https://basarat.gitbook.io/typescript/~gitbook/image?url=https%3A%2F%2Fraw.githubusercontent.com%2Fbasarat%2Ftypescript-book%2Fmaster%2Fimages%2Fdesigntsx-banner.png&width=300&dpr=4&quality=100&sign=74c3ed8&sv=2)](https://designtsx.com/) If you are using TypeScript to create a web application here are my recommendations to get a quick TypeScript + React (my UI framework of choice) project setup. ### [](https://basarat.gitbook.io/typescript/browser#general-machine-setup) General Machine Setup * Install [Node.js](https://nodejs.org/en/download/) * Install [Git](https://git-scm.com/downloads) ### [](https://basarat.gitbook.io/typescript/browser#project-setup-quick) Project Setup Quick Use [https://github.com/basarat/react-typescript](https://github.com/basarat/react-typescript) as a base. Copy git clone https://github.com/basarat/react-typescript.git cd react-typescript npm install Now use it as a base and jump to [develop your amazing application](https://basarat.gitbook.io/typescript/browser#develop-your-amazing-application) ### [](https://basarat.gitbook.io/typescript/browser#project-setup-detailed) Project Setup Detailed If you want to learn more about the details of how that project is created (instead of using it as a base), here are the steps on how its setup from scratch: * Create a project dir: * Create `tsconfig.json`: * Create `package.json`. * Create a `webpack.config.js` to bundle your modules into a single `app.js` file that contains all your resources: * `src/templates/index.html` file. It will be used as the template for the `index.html` generated by webpack. The generated file will be in the `public` folder and and then served from your webserver: * `src/app/app.tsx` that is your frontend application entry point: [](https://basarat.gitbook.io/typescript/browser#develop-your-amazing-application) Develop your amazing application ------------------------------------------------------------------------------------------------------------------------ > You can get the latest packages using `npm install typescript@latest react@latest react-dom@latest @types/react@latest @types/react-dom@latest webpack@latest webpack-dev-server@latest webpack-cli@latest ts-loader@latest clean-webpack-plugin@latest html-webpack-plugin@latest --save-exact` * Do live development by running `npm start`. * Visit [http://localhost:8080](http://localhost:8080/) * Edit the `src/app/app.tsx` (or any ts/tsx file used in some way by `src/app/app.tsx`) and application live reloads. * Edit the `src/templates/index.html` and the server live reloads. * Build production assets by running `npm run build`. * Serve the `public` folder (which contains the built assets) from your server. [PreviousNode.js QuickStart](https://basarat.gitbook.io/typescript/nodejs) [NextLibrary QuickStart](https://basarat.gitbook.io/typescript/library) Last updated 5 years ago * [TypeScript in the browser](https://basarat.gitbook.io/typescript/browser#typescript-in-the-browser) * [General Machine Setup](https://basarat.gitbook.io/typescript/browser#general-machine-setup) * [Project Setup Quick](https://basarat.gitbook.io/typescript/browser#project-setup-quick) * [Project Setup Detailed](https://basarat.gitbook.io/typescript/browser#project-setup-detailed) * [Develop your amazing application](https://basarat.gitbook.io/typescript/browser#develop-your-amazing-application) Copy mkdir your-project cd your-project Copy { "compilerOptions": { "sourceMap": true, "module": "commonjs", "esModuleInterop": true, "resolveJsonModule": true, "experimentalDecorators": true, "target": "es5", "jsx": "react", "lib": [\ "dom",\ "es6"\ ] }, "include": [\ "src"\ ], "compileOnSave": false } Copy { "name": "react-typescript", "version": "0.0.0", "license": "MIT", "repository": { "type": "git", "url": "https://github.com/basarat/react-typescript.git" }, "scripts": { "build": "webpack -p", "start": "webpack-dev-server -d --content-base ./public" }, "dependencies": { "@types/react": "16.4.10", "@types/react-dom": "16.0.7", "clean-webpack-plugin": "0.1.19", "html-webpack-plugin": "3.2.0", "react": "16.4.2", "react-dom": "16.4.2", "ts-loader": "4.4.2", "typescript": "3.0.1", "webpack": "4.16.5", "webpack-cli": "3.1.0", "webpack-dev-server": "3.1.5" } } Copy const { CleanWebpackPlugin } = require('clean-webpack-plugin'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: './src/app/app.tsx', plugins: [\ new CleanWebpackPlugin({\ cleanAfterEveryBuildPatterns: ['public/build']\ }),\ new HtmlWebpackPlugin({\ template: 'src/templates/index.html'\ }),\ ], output: { path: __dirname + '/public', filename: 'build/[name].[contenthash].js' }, resolve: { extensions: ['.ts', '.tsx', '.js'] }, module: { rules: [\ { test: /\.tsx?$/, loader: 'ts-loader' }\ ] } } Copy
Copy import * as React from 'react'; import * as ReactDOM from 'react-dom'; const Hello: React.FunctionComponent<{ compiler: string, framework: string }> = (props) => { return (
{props.compiler}
{props.framework}
); } ReactDOM.render( , document.getElementById("root") ); --- # Dynamic Import Expressions | TypeScript Deep Dive **Dynamic import expressions** are a new feature and part of **ECMAScript** that allows users to asynchronously request a module at any arbitrary point in your program. **TC39** JavaScript committee has itโ€™s own proposal which is in stage 3, and itโ€™s called [import() proposal for JavaScript](https://github.com/tc39/proposal-dynamic-import) . Alternatively, **webpack** bundler has a feature called [**Code Splitting**](https://webpack.js.org/guides/code-splitting/) which allows you to split your bundle into chunks which can be downloaded asynchronously at a later time. For instance, this allows to serve a minimal bootstrap bundle first and to asynchronously load additional features later. Itโ€™s natural to think (if we are using webpack in our dev workflow) that [TypeScript 2.4 dynamic import expressions](https://github.com/Microsoft/TypeScript/wiki/What%27s-new-in-TypeScript#dynamic-import-expressions) will **automatically produce** bundle chunks and automatically code-split your JS final bundle. BUT, that is not as easy as it seems, because it depends on the **tsconfig.json configuration** we are working with. The thing is that webpack code splitting supports two similar techniques to achieve this goal: using **import()** (preferred, ECMAScript proposal) and **require.ensure()** (legacy, webpack specific). And what that means is the expected TypeScript output is **leave the import() statement as it is** instead of transpile it to anything else. Letโ€™s see an example to figure out how to configure webpack + TypeScript 2.4. In the following code I want to **lazy load the library** _**moment**_ but I am interested in code splitting as well, which means, having the moment library in a separate chunk of JS (JavaScript file) that will be loaded only when required. Copy import(/* webpackChunkName: "momentjs" */ "moment") .then((moment) => { // lazyModule has all of the proper types, autocomplete works, // type checking works, code references work \o/ const time = moment().format(); console.log("TypeScript >= 2.4.0 Dynamic Import Expression:"); console.log(time); }) .catch((err) => { console.log("Failed to load moment", err); }); Here is the tsconfig.json: Copy { "compilerOptions": { "target": "es5", "module": "esnext", "lib": [\ "dom",\ "es5",\ "scripthost",\ "es2015.promise"\ ], "jsx": "react", "declaration": false, "sourceMap": true, "outDir": "./dist/js", "strict": true, "moduleResolution": "node", "typeRoots": [\ "./node_modules/@types"\ ], "types": [\ "node",\ "react",\ "react-dom"\ ] } } **Important notes**: * Using **"module": "esnext"** TypeScript produces the mimic import() statement to be input for Webpack Code Splitting. * For further information read this article: [Dynamic Import Expressions and webpack 2 Code Splitting integration with TypeScript 2.4](https://blog.josequinto.com/2017/06/29/dynamic-import-expressions-and-webpack-code-splitting-integration-with-typescript-2-4/) . You can see full example [here](https://cdn.rawgit.com/basarat/typescript-book/705e4496/code/dynamic-import-expressions/dynamicImportExpression.js) . [PreviousNamespaces](https://basarat.gitbook.io/typescript/project/namespaces) [NextNode.js QuickStart](https://basarat.gitbook.io/typescript/nodejs) Last updated 5 years ago --- # Promise | TypeScript Deep Dive [](https://basarat.gitbook.io/typescript/future-javascript/promise#promise) Promise ---------------------------------------------------------------------------------------- The `Promise` class is something that exists in many modern JavaScript engines and can be easily [polyfilled](https://github.com/stefanpenner/es6-promise) . The main motivation for promises is to bring synchronous style error handling to Async / Callback style code. ### [](https://basarat.gitbook.io/typescript/future-javascript/promise#callback-style-code) Callback style code In order to fully appreciate promises let's present a simple sample that proves the difficulty of creating reliable Async code with just callbacks. Consider the simple case of authoring an async version of loading JSON from a file. A synchronous version of this can be quite simple: Copy import fs = require('fs'); function loadJSONSync(filename: string) { return JSON.parse(fs.readFileSync(filename)); } // good json file console.log(loadJSONSync('good.json')); // non-existent file, so fs.readFileSync fails try { console.log(loadJSONSync('absent.json')); } catch (err) { console.log('absent.json error', err.message); } // invalid json file i.e. the file exists but contains invalid JSON so JSON.parse fails try { console.log(loadJSONSync('invalid.json')); } catch (err) { console.log('invalid.json error', err.message); } There are three behaviors of this simple `loadJSONSync` function, a valid return value, a file system error or a JSON.parse error. We handle the errors with a simple try/catch as you are used to when doing synchronous programming in other languages. Now let's make a good async version of such a function. A decent initial attempt with trivial error checking logic would be as follows: Simple enough, it takes a callback, passes any file system errors to the callback. If no file system errors, it returns the `JSON.parse` result. A few points to keep in mind when working with async functions based on callbacks are: 1. Never call the callback twice. 2. Never throw an error. However, this simple function fails to accommodate for point two. In fact, `JSON.parse` throws an error if it is passed bad JSON and the callback never gets called and the application crashes. This is demonstrated in the below example: A naive attempt at fixing this would be to wrap the `JSON.parse` in a try catch as shown in the below example: However, there is a subtle bug in this code. If the callback (`cb`), and not `JSON.parse`, throws an error, since we wrapped it in a `try`/`catch`, the `catch` executes and we call the callback again i.e. the callback gets called twice! This is demonstrated in the example below: This is because our `loadJSON` function wrongfully wrapped the callback in a `try` block. There is a simple lesson to remember here. > Simple lesson: Contain all your sync code in a try catch, except when you call the callback. Following this simple lesson, we have a fully functional async version of `loadJSON` as shown below: Admittedly this is not hard to follow once you've done it a few times but nonetheless itโ€™s a lot of boiler plate code to write simply for good error handling. Now let's look at a better way to tackle asynchronous JavaScript using promises. [](https://basarat.gitbook.io/typescript/future-javascript/promise#creating-a-promise) Creating a Promise -------------------------------------------------------------------------------------------------------------- A promise can be either `pending` or `fulfilled` or `rejected`. ![](https://basarat.gitbook.io/typescript/~gitbook/image?url=https%3A%2F%2Fraw.githubusercontent.com%2Fbasarat%2Ftypescript-book%2Fmaster%2Fimages%2Fpromise%2520states%2520and%2520fates.png&width=768&dpr=4&quality=100&sign=11807ac0&sv=2) promise states and fates Let's look at creating a promise. It's a simple matter of calling `new` on `Promise` (the promise constructor). The promise constructor is passed `resolve` and `reject` functions for settling the promise state: ### [](https://basarat.gitbook.io/typescript/future-javascript/promise#subscribing-to-the-fate-of-the-promise) Subscribing to the fate of the promise The promise fate can be subscribed to using `.then` (if resolved) or `.catch` (if rejected). > TIP: Promise Shortcuts > > * Quickly creating an already resolved promise: `Promise.resolve(result)` > > * Quickly creating an already rejected promise: `Promise.reject(error)` > ### [](https://basarat.gitbook.io/typescript/future-javascript/promise#chain-ability-of-promises) Chain-ability of Promises The chain-ability of promises **is the heart of the benefit that promises provide**. Once you have a promise, from that point on, you use the `then` function to create a chain of promises. * If you return a promise from any function in the chain, `.then` is only called once the value is resolved: * You can aggregate the error handling of any preceding portion of the chain with a single `catch`: * The `catch` actually returns a new promise (effectively creating a new promise chain): * Any synchronous errors thrown in a `then` (or `catch`) result in the returned promise to fail: * Only the relevant (nearest tailing) `catch` is called for a given error (as the catch starts a new promise chain). * A `catch` is only called in case of an error in the preceding chain: The fact that: * errors jump to the tailing `catch` (and skip any middle `then` calls) and * synchronous errors also get caught by any tailing `catch`. effectively provides us with an async programming paradigm that allows better error handling than raw callbacks. More on this below. ### [](https://basarat.gitbook.io/typescript/future-javascript/promise#typescript-and-promises) TypeScript and promises The great thing about TypeScript is that it understands the flow of values through a promise chain: Of course it also understands unwrapping any function calls that might return a promise: ### [](https://basarat.gitbook.io/typescript/future-javascript/promise#converting-a-callback-style-function-to-return-a-promise) Converting a callback style function to return a promise Just wrap the function call in a promise and * `reject` if an error occurs, * `resolve` if it is all good. E.g. let's wrap `fs.readFile`: The most reliable way to do this is to hand write it and it doesn't have to be as verbose as the previous example e.g. converting `setTimeout` into a promisified `delay` function is super easy: Note that there is a handy dandy function in NodeJS that does this `node style function => promise returning function` magic for you: > Webpack supports the `util` module out of the box and you can use it in the browser as well. If you have a node callback style function as a _member_ be sure to `bind` it as well to make sure it has the correct `this`: ### [](https://basarat.gitbook.io/typescript/future-javascript/promise#revisiting-the-json-example) Revisiting the JSON example Now let's revisit our `loadJSON` example and rewrite an async version that uses promises. All that we need to do is read the file contents as a promise, then parse them as JSON and we are done. This is illustrated in the below example: Usage (notice how similar it is to the original `sync` version introduced at the start of this section ๐ŸŒน): The reason why this function was simpler is because the "`loadFile`(async) + `JSON.parse` (sync) => `catch`" consolidation was done by the promise chain. Also the callback was not called by _us_ but called by the promise chain so we didn't have the chance of making the mistake of wrapping it in a `try/catch`. ### [](https://basarat.gitbook.io/typescript/future-javascript/promise#parallel-control-flow) Parallel control flow We have seen how trivial doing a serial sequence of async tasks is with promises. It is simply a matter of chaining `then` calls. However, you might potentially want to run a series of async tasks and then do something with the results of all of these tasks. `Promise` provides a static `Promise.all` function that you can use to wait for `n` number of promises to complete. You provide it with an array of `n` promises and it gives you an array of `n` resolved values. Below we show Chaining as well as Parallel: Sometimes, you want to run a series of async tasks, but you get all you need as long as any one of these tasks is settled. `Promise` provides a static `Promise.race` function for this scenario: [PreviousTemplate Strings](https://basarat.gitbook.io/typescript/future-javascript/template-strings) [NextGenerators](https://basarat.gitbook.io/typescript/future-javascript/generators) Last updated 5 years ago * [Promise](https://basarat.gitbook.io/typescript/future-javascript/promise#promise) * [Callback style code](https://basarat.gitbook.io/typescript/future-javascript/promise#callback-style-code) * [Creating a Promise](https://basarat.gitbook.io/typescript/future-javascript/promise#creating-a-promise) * [Subscribing to the fate of the promise](https://basarat.gitbook.io/typescript/future-javascript/promise#subscribing-to-the-fate-of-the-promise) * [Chain-ability of Promises](https://basarat.gitbook.io/typescript/future-javascript/promise#chain-ability-of-promises) * [TypeScript and promises](https://basarat.gitbook.io/typescript/future-javascript/promise#typescript-and-promises) * [Converting a callback style function to return a promise](https://basarat.gitbook.io/typescript/future-javascript/promise#converting-a-callback-style-function-to-return-a-promise) * [Revisiting the JSON example](https://basarat.gitbook.io/typescript/future-javascript/promise#revisiting-the-json-example) * [Parallel control flow](https://basarat.gitbook.io/typescript/future-javascript/promise#parallel-control-flow) Copy import fs = require('fs'); // A decent initial attempt .... but not correct. We explain the reasons below function loadJSON(filename: string, cb: (error: Error, data: any) => void) { fs.readFile(filename, function (err, data) { if (err) cb(err); else cb(null, JSON.parse(data)); }); } Copy import fs = require('fs'); // A decent initial attempt .... but not correct function loadJSON(filename: string, cb: (error: Error, data: any) => void) { fs.readFile(filename, function (err, data) { if (err) cb(err); else cb(null, JSON.parse(data)); }); } // load invalid json loadJSON('invalid.json', function (err, data) { // This code never executes if (err) console.log('bad.json error', err.message); else console.log(data); }); Copy import fs = require('fs'); // A better attempt ... but still not correct function loadJSON(filename: string, cb: (error: Error) => void) { fs.readFile(filename, function (err, data) { if (err) { cb(err); } else { try { cb(null, JSON.parse(data)); } catch (err) { cb(err); } } }); } // load invalid json loadJSON('invalid.json', function (err, data) { if (err) console.log('bad.json error', err.message); else console.log(data); }); Copy import fs = require('fs'); function loadJSON(filename: string, cb: (error: Error) => void) { fs.readFile(filename, function (err, data) { if (err) { cb(err); } else { try { cb(null, JSON.parse(data)); } catch (err) { cb(err); } } }); } // a good file but a bad callback ... gets called again! loadJSON('good.json', function (err, data) { console.log('our callback called'); if (err) console.log('Error:', err.message); else { // let's simulate an error by trying to access a property on an undefined variable var foo; // The following code throws `Error: Cannot read property 'bar' of undefined` console.log(foo.bar); } }); Copy $ node asyncbadcatchdemo.js our callback called our callback called Error: Cannot read property 'bar' of undefined Copy import fs = require('fs'); function loadJSON(filename: string, cb: (error: Error) => void) { fs.readFile(filename, function (err, data) { if (err) return cb(err); // Contain all your sync code in a try catch try { var parsed = JSON.parse(data); } catch (err) { return cb(err); } // except when you call the callback return cb(null, parsed); }); } Copy const promise = new Promise((resolve, reject) => { // the resolve / reject functions control the fate of the promise }); Copy const promise = new Promise((resolve, reject) => { resolve(123); }); promise.then((res) => { console.log('I get called:', res === 123); // I get called: true }); promise.catch((err) => { // This is never called }); Copy const promise = new Promise((resolve, reject) => { reject(new Error("Something awful happened")); }); promise.then((res) => { // This is never called }); promise.catch((err) => { console.log('I get called:', err.message); // I get called: 'Something awful happened' }); Copy Promise.resolve(123) .then((res) => { console.log(res); // 123 return 456; }) .then((res) => { console.log(res); // 456 return Promise.resolve(123); // Notice that we are returning a Promise }) .then((res) => { console.log(res); // 123 : Notice that this `then` is called with the resolved value return 123; }) Copy // Create a rejected promise Promise.reject(new Error('something bad happened')) .then((res) => { console.log(res); // not called return 456; }) .then((res) => { console.log(res); // not called return 123; }) .then((res) => { console.log(res); // not called return 123; }) .catch((err) => { console.log(err.message); // something bad happened }); Copy // Create a rejected promise Promise.reject(new Error('something bad happened')) .then((res) => { console.log(res); // not called return 456; }) .catch((err) => { console.log(err.message); // something bad happened return 123; }) .then((res) => { console.log(res); // 123 }) Copy Promise.resolve(123) .then((res) => { throw new Error('something bad happened'); // throw a synchronous error return 456; }) .then((res) => { console.log(res); // never called return Promise.resolve(789); }) .catch((err) => { console.log(err.message); // something bad happened }) Copy Promise.resolve(123) .then((res) => { throw new Error('something bad happened'); // throw a synchronous error return 456; }) .catch((err) => { console.log('first catch: ' + err.message); // something bad happened return 123; }) .then((res) => { console.log(res); // 123 return Promise.resolve(789); }) .catch((err) => { console.log('second catch: ' + err.message); // never called }) Copy Promise.resolve(123) .then((res) => { return 456; }) .catch((err) => { console.log("HERE"); // never called }) Copy Promise.resolve(123) .then((res) => { // res is inferred to be of type `number` return true; }) .then((res) => { // res is inferred to be of type `boolean` }); Copy function iReturnPromiseAfter1Second(): Promise { return new Promise((resolve) => { setTimeout(() => resolve("Hello world!"), 1000); }); } Promise.resolve(123) .then((res) => { // res is inferred to be of type `number` return iReturnPromiseAfter1Second(); // We are returning `Promise` }) .then((res) => { // res is inferred to be of type `string` console.log(res); // Hello world! }); Copy import fs = require('fs'); function readFileAsync(filename: string): Promise { return new Promise((resolve,reject) => { fs.readFile(filename,(err,result) => { if (err) reject(err); else resolve(result); }); }); } Copy const delay = (ms: number) => new Promise(res => setTimeout(res, ms)); Copy /** Sample usage */ import fs from 'fs'; import util from 'util'; const readFile = util.promisify(fs.readFile); Copy const dbGet = util.promisify(db.get).bind(db); Copy function loadJSONAsync(filename: string): Promise { return readFileAsync(filename) // Use the function we just wrote .then(function (res) { return JSON.parse(res); }); } Copy // good json file loadJSONAsync('good.json') .then(function (val) { console.log(val); }) .catch(function (err) { console.log('good.json error', err.message); // never called }) // non-existent json file .then(function () { return loadJSONAsync('absent.json'); }) .then(function (val) { console.log(val); }) // never called .catch(function (err) { console.log('absent.json error', err.message); }) // invalid json file .then(function () { return loadJSONAsync('invalid.json'); }) .then(function (val) { console.log(val); }) // never called .catch(function (err) { console.log('bad.json error', err.message); }); Copy // an async function to simulate loading an item from some server function loadItem(id: number): Promise<{ id: number }> { return new Promise((resolve) => { console.log('loading item', id); setTimeout(() => { // simulate a server delay resolve({ id: id }); }, 1000); }); } // Chained / Sequential let item1, item2; loadItem(1) .then((res) => { item1 = res; return loadItem(2); }) .then((res) => { item2 = res; console.log('done'); }); // overall time will be around 2s // Concurrent / Parallel Promise.all([loadItem(1), loadItem(2)]) .then((res) => { [item1, item2] = res; console.log('done'); }); // overall time will be around 1s Copy var task1 = new Promise(function(resolve, reject) { setTimeout(resolve, 1000, 'one'); }); var task2 = new Promise(function(resolve, reject) { setTimeout(resolve, 2000, 'two'); }); Promise.race([task1, task2]).then(function(value) { console.log(value); // "one" // Both resolve, but task1 resolves faster }); --- # Generators | TypeScript Deep Dive `function *` is the syntax used to create a _generator function_. Calling a generator function returns a _generator object_. The generator object just follows the [iterator](https://basarat.gitbook.io/typescript/future-javascript/iterators) interface (i.e. the `next`, `return` and `throw` functions). There are two key motivations behind generator functions: [](https://basarat.gitbook.io/typescript/future-javascript/generators#lazy-iterators) Lazy Iterators --------------------------------------------------------------------------------------------------------- Generator functions can be used to create lazy iterators e.g. the following function returns an **infinite** list of integers on demand: Copy function* infiniteSequence() { var i = 0; while(true) { yield i++; } } var iterator = infiniteSequence(); while (true) { console.log(iterator.next()); // { value: xxxx, done: false } forever and ever } Of course if the iterator does end, you get the result of `{ done: true }` as demonstrated below: Copy function* idMaker(){ let index = 0; while(index < 3) yield index++; } let gen = idMaker(); console.log(gen.next()); // { value: 0, done: false } console.log(gen.next()); // { value: 1, done: false } console.log(gen.next()); // { value: 2, done: false } console.log(gen.next()); // { done: true } [](https://basarat.gitbook.io/typescript/future-javascript/generators#externally-controlled-execution) Externally Controlled Execution ------------------------------------------------------------------------------------------------------------------------------------------- This is the part of generators that is truly exciting. It essentially allows a function to pause its execution and pass control (fate) of the remainder of the function execution to the caller. A generator function does not execute when you call it. It just creates a generator object. Consider the following example along with a sample execution: If you run this you get the following output: * The function only starts execution once `next` is called on the generator object. * The function _pauses_ as soon as a `yield` statement is encountered. * The function _resumes_ when `next` is called. > So essentially the execution of the generator function is controllable by the generator object. Our communication using the generator has been mostly one way with the generator returning values for the iterator. One extremely powerful feature of generators in JavaScript is that they allow two way communications (with caveats). * you can control the resulting value of the `yield` expression using `iterator.next(valueToInject)` * you can throw an exception at the point of the `yield` expression using `iterator.throw(error)` The following example demonstrates `iterator.next(valueToInject)`: Since `yield` returns the parameter passed to the iterator's `next` function, and all iterators' `next` functions accept a parameter of any type, TypeScript will always assign the `any` type to the result of the `yield` operator (`bar` above). > You are on your own to coerce the result to the type you expect, and ensure that only values of that type are passed to next (such as by scaffolding an additional type-enforcement layer that calls `next` for you.) If strong typing is important to you, you may want to avoid two-way communication altogether, as well as packages that rely heavily on it (e.g., redux-saga). The following example demonstrates `iterator.throw(error)`: So here is the summary: * `yield` allows a generator function to pause its communication and pass control to an external system * the external system can push a value into the generator function body * the external system can throw an exception into the generator function body How is this useful? Jump to the next section [**async/await**](https://basarat.gitbook.io/typescript/future-javascript/async-await) and find out. [PreviousPromise](https://basarat.gitbook.io/typescript/future-javascript/promise) [NextAsync Await](https://basarat.gitbook.io/typescript/future-javascript/async-await) Last updated 5 years ago * [Lazy Iterators](https://basarat.gitbook.io/typescript/future-javascript/generators#lazy-iterators) * [Externally Controlled Execution](https://basarat.gitbook.io/typescript/future-javascript/generators#externally-controlled-execution) Copy function* generator(){ console.log('Execution started'); yield 0; console.log('Execution resumed'); yield 1; console.log('Execution resumed'); } var iterator = generator(); console.log('Starting iteration'); // This will execute before anything in the generator function body executes console.log(iterator.next()); // { value: 0, done: false } console.log(iterator.next()); // { value: 1, done: false } console.log(iterator.next()); // { value: undefined, done: true } Copy $ node outside.js Starting iteration Execution started { value: 0, done: false } Execution resumed { value: 1, done: false } Execution resumed { value: undefined, done: true } Copy function* generator() { const bar = yield 'foo'; // bar may be *any* type console.log(bar); // bar! } const iterator = generator(); // Start execution till we get first yield value const foo = iterator.next(); console.log(foo.value); // foo // Resume execution injecting bar const nextThing = iterator.next('bar'); Copy function* generator() { try { yield 'foo'; } catch(err) { console.log(err.message); // bar! } } var iterator = generator(); // Start execution till we get first yield value var foo = iterator.next(); console.log(foo.value); // foo // Resume execution throwing an exception 'bar' var nextThing = iterator.throw(new Error('bar')); --- # JSX | TypeScript Deep Dive [![DesignTSX](https://basarat.gitbook.io/typescript/~gitbook/image?url=https%3A%2F%2Fraw.githubusercontent.com%2Fbasarat%2Ftypescript-book%2Fmaster%2Fimages%2Fdesigntsx-banner.png&width=300&dpr=4&quality=100&sign=74c3ed8&sv=2)](https://designtsx.com/) TypeScript supports JSX transpilation and code analysis. If you are unfamiliar with JSX here is an excerpt from the [official website](https://facebook.github.io/jsx/) : > JSX is an XML-like syntax extension to ECMAScript without any defined semantics. It's NOT intended to be implemented by engines or browsers. It's NOT a proposal to incorporate JSX into the ECMAScript spec itself. It's intended to be used by various preprocessors (transpilers) to transform these tokens into standard ECMAScript. The motivation behind JSX is to allow users to write HTML like views _in JavaScript_ so that you can: * Have the view Type Checked by the same code that is going to check your JavaScript * Have the view be aware of the context it is going to operate under (i.e. strengthen the _controller-view_ connection in traditional MVC). * Reuse JavaScript patterns for HTML maintenance e.g. `Array.prototype.map`, `?:`, `switch` etc instead of creating new (and probably poorly typed) alternatives. This decreases the chances of errors and increases the maintainability of your user interfaces. The main consumer of JSX at this point is [ReactJS from facebook](http://facebook.github.io/react/) . This is the usage of JSX that we will discuss here. [PreviousMixins](https://basarat.gitbook.io/typescript/type-system/mixins) [NextReact](https://basarat.gitbook.io/typescript/tsx/react) Last updated 5 years ago --- # Options | TypeScript Deep Dive There are a few things that TypeScript prevents you from doing out of the box e.g. using a variable that _isn't ever declared_ (of course you can use a _declaration file_ for external systems). That said, traditionally programming languages have a hard boundary between what is and isn't allowed by the type system. TypeScript is different in that it gives you control over where you put the slider. This is really to allow you to use the JavaScript you know and love with as much safety as **you** want. There are lots of compiler options to control exactly this slider so let's have a look. [](https://basarat.gitbook.io/typescript/intro#boolean-options) Boolean Options ------------------------------------------------------------------------------------ `compilerOptions` that are `boolean` can be specified as `compilerOptions` in `tsconfig.json`: Copy { "compilerOptions": { "someBooleanOption": true } } or on the command line Copy tsc --someBooleanOption > All of these are `false` by default. Click [here](https://www.typescriptlang.org/docs/handbook/compiler-options.html) to see all compiler options. [PreviousNon React JSX](https://basarat.gitbook.io/typescript/tsx/others) [NextnoImplicitAny](https://basarat.gitbook.io/typescript/intro/noimplicitany) Last updated 5 years ago --- # Errors in TypeScript | TypeScript Deep Dive In this section we discuss how to read and understand TypeScript errors. We follow this with common errors and their solutions. [PreviousstrictNullChecks](https://basarat.gitbook.io/typescript/intro/strictnullchecks) [NextInterpreting Errors](https://basarat.gitbook.io/typescript/main/interpreting-errors) Last updated 5 years ago --- # noImplicitAny | TypeScript Deep Dive There are some things that cannot be inferred or inferring them might result in unexpected errors. A fine example is function arguments. If you don't annotate them, its unclear what should and shouldn't be valid e.g. Copy function log(someArg) { sendDataToServer(someArg); } // What arg is valid and what isn't? log(123); log('hello world'); So if you don't annotate some function argument, TypeScript assumes `any` and moves on. This essentially turns off type checking for such cases, which is what a JavaScript dev would expect. But this can catch people that want high safety off guard. Hence there is an option, `noImplicitAny`, that when switched on will flag the cases where the type cannot be inferred e.g. Copy function log(someArg) { // Error : someArg has an implicit `any` type sendDataToServer(someArg); } Of course you can then go ahead and annotate: Copy function log(someArg: number) { sendDataToServer(someArg); } And if you truly want _zero safety_ you can mark it _explicitly_ as `any`: Copy function log(someArg: any) { sendDataToServer(someArg); } [PreviousOptions](https://basarat.gitbook.io/typescript/intro) [NextstrictNullChecks](https://basarat.gitbook.io/typescript/intro/strictnullchecks) Last updated 5 years ago --- # Testing | TypeScript Deep Dive TypeScript can be used with any JavaScript testing framework that you want. In the worst case you can always do a simple `TypeScript -> JavaScript` transform and go your merry way. That said, in this section look at options that we have enjoyed greatly ๐ŸŒน [PreviousNPM](https://basarat.gitbook.io/typescript/index) [NextJest](https://basarat.gitbook.io/typescript/intro-1/jest) Last updated 5 years ago --- # strictNullChecks | TypeScript Deep Dive By default `null` and `undefined` are assignable to all types in TypeScript e.g. Copy let foo: number = 123; foo = null; // Okay foo = undefined; // Okay This is modelled after how a lot of people write JavaScript. However, like all things, TypeScript allows you to be _explicit_ about what _can and cannot be_ assigned a `null` or `undefined`. In strict null checking mode, `null` and `undefined` are different: Copy let foo = undefined; foo = null; // NOT Okay Let's say we have a `Member` interface: Copy interface Member { name: string, age?: number } Not every `Member` will provide their age, so `age` is an optional property, meaning the value of `age` may or may not be `undefined`. `undefined` is the root of all evil. It often leads to runtime errors. It is easy to write code that will throw `Error` at runtime: Copy getMember() .then(member: Member => { const stringifyAge = member.age.toString() // Cannot read property 'toString' of undefined }) But in strict null checking mode, this error will be caught at compile time: [](https://basarat.gitbook.io/typescript/intro/strictnullchecks#non-null-assertion-operator) Non-Null Assertion Operator ----------------------------------------------------------------------------------------------------------------------------- A new `!` post-fix expression operator may be used to assert that its operand is non-null and non-undefined in contexts where the type checker is unable to conclude that fact. For example: > Note that it is just an assertion, and just like type assertions _you are responsible_ for making sure the value is not null. A non-null assertion is essentially you telling the compiler "I know it's not null so let me use it as though it's not null". ### [](https://basarat.gitbook.io/typescript/intro/strictnullchecks#definite-assignment-assertion-operator) Definite Assignment Assertion Operator TypeScript will also complain about properties in classes not being initialized e.g.: You can use the definite assignment assertion postfixed to the property name to tell TypeScript that you are initializing it somewhere other than the constructor e.g. You can also use this assertion with simple variable declarations e.g.: > Like all assertions, you are telling the compiler to trust you. The compiler will not complain even if the code doesn't actually always assign the property. [PreviousnoImplicitAny](https://basarat.gitbook.io/typescript/intro/noimplicitany) [NextErrors in TypeScript](https://basarat.gitbook.io/typescript/main) Last updated 5 years ago * [Non-Null Assertion Operator](https://basarat.gitbook.io/typescript/intro/strictnullchecks#non-null-assertion-operator) * [Definite Assignment Assertion Operator](https://basarat.gitbook.io/typescript/intro/strictnullchecks#definite-assignment-assertion-operator) Copy getMember() .then(member: Member => { const stringifyAge = member.age.toString() // Object is possibly 'undefined' }) Copy // Compiled with --strictNullChecks function validateEntity(e?: Entity) { // Throw exception if e is null or invalid entity } function processEntity(e?: Entity) { validateEntity(e); let a = e.name; // TS ERROR: e may be null. let b = e!.name; // OKAY. We are asserting that e is non-null. } Copy class C { foo: number; // OKAY as assigned in constructor bar: string = "hello"; // OKAY as has property initializer baz: boolean; // TS ERROR: Property 'baz' has no initializer and is not assigned directly in the constructor. constructor() { this.foo = 42; } } Copy class C { foo!: number; // ^ // Notice this exclamation point! // This is the "definite assignment assertion" modifier. constructor() { this.initialize(); } initialize() { this.foo = 0; } } Copy let a: number[]; // No assertion let b!: number[]; // Assert initialize(); a.push(4); // TS ERROR: variable used before assignment b.push(4); // OKAY: because of the assertion function initialize() { a = [0, 1, 2, 3]; b = [0, 1, 2, 3]; } --- # React | TypeScript Deep Dive > [Free series of youtube videos on React / TypeScript best practices](https://www.youtube.com/watch?v=7EW67MqgJvs&list=PLYvdvJlnTOjHNayH7MukKbSJ6PueUNkkG) > > [PRO Egghead course on TypeScript and React](https://egghead.io/courses/use-typescript-to-develop-react-applications) [![DesignTSX](https://basarat.gitbook.io/typescript/~gitbook/image?url=https%3A%2F%2Fraw.githubusercontent.com%2Fbasarat%2Ftypescript-book%2Fmaster%2Fimages%2Fdesigntsx-banner.png&width=300&dpr=4&quality=100&sign=74c3ed8&sv=2)](https://designtsx.com/) [](https://basarat.gitbook.io/typescript/tsx/react#setup) Setup -------------------------------------------------------------------- Our [browser quickstart already sets you up to develop react applications](https://basarat.gitbook.io/typescript/browser) . Here are the key highlights. * Use files with the extension `.tsx` (instead of `.ts`). * Use `"jsx" : "react"` in your `tsconfig.json`'s `compilerOptions`. * Install the definitions for JSX and React into your project : (`npm i -D @types/react @types/react-dom`). * Import react into your `.tsx` files (`import * as React from "react"`). [](https://basarat.gitbook.io/typescript/tsx/react#html-tags-vs.-components) HTML Tags vs. Components ---------------------------------------------------------------------------------------------------------- React can either render HTML tags (strings) or React components. The JavaScript emit for these elements is different (`React.createElement('div')` vs. `React.createElement(MyComponent)`). The way this is determined is by the _case_ of the _first_ letter. `foo` is treated as an HTML tag and `Foo` is treated as a component. [](https://basarat.gitbook.io/typescript/tsx/react#type-checking) Type Checking ------------------------------------------------------------------------------------ ### [](https://basarat.gitbook.io/typescript/tsx/react#html-tags) HTML Tags An HTML Tag `foo` is to be of the type `JSX.IntrinsicElements.foo`. These types are already defined for all the major tags in a file `react-jsx.d.ts` which we had you install as a part of the setup. Here is a sample of the the contents of the file: ### [](https://basarat.gitbook.io/typescript/tsx/react#function-components) Function Components You can define function components simply with the `React.FunctionComponent` interface e.g. ### [](https://basarat.gitbook.io/typescript/tsx/react#void-function-components) Void Function Components As of [@types/react PR #46643](https://github.com/DefinitelyTyped/DefinitelyTyped/pull/46643) , you can use a new `React.VoidFunctionComponent` or `React.VFC` type if you wish to declare that a component does not take `children`. This is an interim solution until the next major version of the type defs (where VoidFunctionComponent will be deprecated and FunctionComponent will by default accept no children). ### [](https://basarat.gitbook.io/typescript/tsx/react#class-components) Class Components Components are type checked based on the `props` property of the component. This is modeled after how JSX is transformed i.e. the attributes become the `props` of the component. The `react.d.ts` file defines the `React.Component` class which you should extend in your own class providing your own `Props` and `State` interfaces. This is demonstrated below: ### [](https://basarat.gitbook.io/typescript/tsx/react#react-jsx-tip-interface-for-renderable) React JSX Tip: Interface for renderable React can render a few things like `JSX` or `string`. These are all consolidated into the type `React.ReactNode` so use it for when you want to accept renderables e.g. ### [](https://basarat.gitbook.io/typescript/tsx/react#react-jsx-tip-accept-an-instance-of-a-component) React JSX Tip: Accept an instance of a Component The react type definitions provide `React.ReactElement` to allow you to annotate the result of a `` class component instantiation. e.g. > Of course you can use this as a function argument annotation and even React component prop member. ### [](https://basarat.gitbook.io/typescript/tsx/react#react-jsx-tip-accept-a-component-that-can-act-on-props-and-be-rendered-using-jsx) React JSX Tip: Accept a _component_ that can act on props and be rendered using JSX The type `React.Component` consolidates `React.ComponentClass

| React.StatelessComponent

` so you can accept _something_ that takes type `Props` and renders it using JSX e.g. ### [](https://basarat.gitbook.io/typescript/tsx/react#react-jsx-tip-generic-components) React JSX Tip: Generic components It works exactly as expected. Here is an example: ### [](https://basarat.gitbook.io/typescript/tsx/react#generic-functions) Generic functions Something like the following works fine: However, using an arrow generic function will not: **Workaround**: Use `extends` on the generic parameter to hint the compiler that it's a generic, e.g.: ### [](https://basarat.gitbook.io/typescript/tsx/react#react-tip-strongly-typed-refs) React Tip: Strongly Typed Refs You basically initialize a variable as a union of the ref and `null` and then initialize it as as callback e.g. And the same with ref's for native elements e.g. ### [](https://basarat.gitbook.io/typescript/tsx/react#type-assertions) Type Assertions Use `as Foo` syntax for type assertions as we [mentioned before](https://basarat.gitbook.io/typescript/type-system/type-assertion#as-foo-vs-foo) . [](https://basarat.gitbook.io/typescript/tsx/react#default-props) Default Props ------------------------------------------------------------------------------------ * Stateful components with default props: You can tell TypeScript that a property will be provided externally (by React) by using a _null assertion_ operator (this isn't ideal but is the simplest minimum _extra code_ solution I could think of). * SFC with default props: Recommend leveraging simple JavaScript patterns as they work well with TypeScript's type system e.g. [](https://basarat.gitbook.io/typescript/tsx/react#declaring-a-webcomponent) Declaring a webcomponent ---------------------------------------------------------------------------------------------------------- If you are using a web component the default React type definitions (`@types/react`) will not know about it. But you can declare it easily e.g. to declare a webcomponent called `my-awesome-slider` that takes Props `MyAwesomeSliderProps` you would: Now you can use it in TSX: [PreviousJSX](https://basarat.gitbook.io/typescript/tsx) [NextNon React JSX](https://basarat.gitbook.io/typescript/tsx/others) Last updated 5 years ago * [Setup](https://basarat.gitbook.io/typescript/tsx/react#setup) * [HTML Tags vs. Components](https://basarat.gitbook.io/typescript/tsx/react#html-tags-vs.-components) * [Type Checking](https://basarat.gitbook.io/typescript/tsx/react#type-checking) * [HTML Tags](https://basarat.gitbook.io/typescript/tsx/react#html-tags) * [Function Components](https://basarat.gitbook.io/typescript/tsx/react#function-components) * [Void Function Components](https://basarat.gitbook.io/typescript/tsx/react#void-function-components) * [Class Components](https://basarat.gitbook.io/typescript/tsx/react#class-components) * [React JSX Tip: Interface for renderable](https://basarat.gitbook.io/typescript/tsx/react#react-jsx-tip-interface-for-renderable) * [React JSX Tip: Accept an instance of a Component](https://basarat.gitbook.io/typescript/tsx/react#react-jsx-tip-accept-an-instance-of-a-component) * [React JSX Tip: Accept a component that can act on props and be rendered using JSX](https://basarat.gitbook.io/typescript/tsx/react#react-jsx-tip-accept-a-component-that-can-act-on-props-and-be-rendered-using-jsx) * [React JSX Tip: Generic components](https://basarat.gitbook.io/typescript/tsx/react#react-jsx-tip-generic-components) * [Generic functions](https://basarat.gitbook.io/typescript/tsx/react#generic-functions) * [React Tip: Strongly Typed Refs](https://basarat.gitbook.io/typescript/tsx/react#react-tip-strongly-typed-refs) * [Type Assertions](https://basarat.gitbook.io/typescript/tsx/react#type-assertions) * [Default Props](https://basarat.gitbook.io/typescript/tsx/react#default-props) * [Declaring a webcomponent](https://basarat.gitbook.io/typescript/tsx/react#declaring-a-webcomponent) Copy declare module JSX { interface IntrinsicElements { a: React.HTMLAttributes; abbr: React.HTMLAttributes; div: React.HTMLAttributes; span: React.HTMLAttributes; /// so on ... } } Copy type Props = { foo: string; } const MyComponent: React.FunctionComponent = (props) => { return {props.foo} } Copy type Props = { foo: string } // OK now, in future, error const FunctionComponent: React.FunctionComponent = ({ foo, children }: Props) => { return

{foo} {children}
; // OK }; // Error now (children not support), in future, deprecated const VoidFunctionComponent: React.VoidFunctionComponent = ({ foo, children }) => { return
{foo}{children}
; }; Copy type Props = { foo: string; } class MyComponent extends React.Component { render() { return {this.props.foo} } } Copy type Props = { header: React.ReactNode; body: React.ReactNode; } class MyComponent extends React.Component { render() { return
{this.props.header} {this.props.body}
; } } Header} body={body} /> Copy class MyAwesomeComponent extends React.Component { render() { return
Hello
; } } const foo: React.ReactElement = ; // Okay const bar: React.ReactElement = ; // Error! Copy const X: React.Component = foo; // from somewhere // Render X with some props: ; Copy /** A generic component */ type SelectProps = { items: T[] } class Select extends React.Component, any> { } /** Usage */ const Form = () => items={['a','b']} />; Copy function foo(x: T): T { return x; } Copy const foo = (x: T) => x; // ERROR : unclosed `T` tag Copy const foo = (x: T) => x; Copy class Example extends React.Component { example() { // ... something } render() { return
Foo
} } class Use { exampleRef: Example | null = null; render() { return this.exampleRef = exampleRef } /> } } Copy class FocusingInput extends React.Component<{ value: string, onChange: (value: string) => any }, {}>{ input: HTMLInputElement | null = null; render() { return ( this.input = input} value={this.props.value} onChange={(e) => { this.props.onChange(e.target.value) } } /> ); } focus() { if (this.input != null) { this.input.focus() } } } Copy class Hello extends React.Component<{ /** * @default 'TypeScript' */ compiler?: string, framework: string }> { static defaultProps = { compiler: 'TypeScript' } render() { const compiler = this.props.compiler!; return (
{compiler}
{this.props.framework}
); } } ReactDOM.render( , // TypeScript React document.getElementById("root") ); Copy const Hello: React.SFC<{ /** * @default 'TypeScript' */ compiler?: string, framework: string }> = ({ compiler = 'TypeScript', // Default prop framework }) => { return (
{compiler}
{framework}
); }; ReactDOM.render( , // TypeScript React document.getElementById("root") ); Copy declare global { namespace JSX { interface IntrinsicElements { 'my-awesome-slider': MyAwesomeSliderProps; } interface MyAwesomeSliderProps extends React.Attributes { name: string; } } } Copy --- # NPM | TypeScript Deep Dive > Fun fact `npm` is [not an acronym](https://twitter.com/npmjs/status/347057301401763840) > so it doesn't expand to anything, but among friends it is commonly called `node package manager`. `npm` is a binary that comes with default `node` installations used to manage community shared JavaScript / TypeScript packages. * NPM packages are hosted at (and installed from) [https://www.npmjs.com/](https://www.npmjs.com/) (the โ˜๏ธ). [](https://basarat.gitbook.io/typescript/index#quick-common-setup) Quick common setup ------------------------------------------------------------------------------------------ * npm packages are configured using `package.json` file. You can generate a quick file using `npm init -y`. * packages get installed into a `./node_modules` folder. You normally have this folder in your `.gitignore`. > Even though you might be building an application, having a `package.json` essentially makes your project a package as well. So the terms your `project | package` can be used interchangeably. When you checkout someone's (your team's) package, it will have a `package.json` that will list the dependencies you need to run the project. You simply run `npm install` and npm will bring them down from the cloud โ˜๏ธ. [](https://basarat.gitbook.io/typescript/index#installing-a-package) Installing a package ---------------------------------------------------------------------------------------------- You can run `npm install `. Most people will use the shorthand `npm i ` e.g. Copy // Install react npm i react > This will also automatically add `react` into your `package.json`'s `dependencies`. [](https://basarat.gitbook.io/typescript/index#installing-a-devdependency) Installing a devDependency ---------------------------------------------------------------------------------------------------------- `devDependencies` are dependencies that are only required during _development_ if your project and not required after deployment. `typescript` is common in `devDependencies` as its only required to build `.ts -> .js`. You normally deploy the built `.js` files: * into production * OR for consumption by other other npm packages [](https://basarat.gitbook.io/typescript/index#security) Security ---------------------------------------------------------------------- The public `npm` packages are scanned by security team worldwide and issues get reported to npm team. They then release security advisories detailing the issue and potential fixes. Commonly the fix is simply updating the package. You can run an audit on your node project by simply running `npm audit`. This will highlight any vulnerabilities that might exist in the package / dependencies of the package. e.g. Note that commonly the issues are found in _development_ dependencies (e.g. jest in this case). Since these aren't are a part of your production deployments, most likely your production application is not vulnerable. But still good practice to keep vulnerabilities to `0`. Simply add `npm audit` (the command exist with error code `1` in case of error) as a part of your deployment to ensure the projects stay up to date. [](https://basarat.gitbook.io/typescript/index#npm-scripts) NPM Scripts ---------------------------------------------------------------------------- ### [](https://basarat.gitbook.io/typescript/index#what-is-with-in-scripts) What is with `--` in scripts You can build a base script with a limited set of command line arguments e.g. here is a script target that runs `tsc` for the TypeScript compiler: You can create a `build:watch` target to run `tsc -p . -w` or alternatively asking npm to run `build` with the additional `-w` flag like so: You can pass in as many flags as you want after `--` e.g. in the following example `build:more` has the same effect as `something --foo -f -d --bar` [](https://basarat.gitbook.io/typescript/index#public-vs.-private-packages) Public vs. Private packages ------------------------------------------------------------------------------------------------------------ You don't need this when _using_ any of the common public npm packages. Just know its there for enterprise / commercial customers. ### [](https://basarat.gitbook.io/typescript/index#public-packages) Public packages * Packages are public by default. * Anyone can deploy a package to npm. * You just need an account (which you can get for free). No one needs an account to download a public package. This free sharing of packages is one of the key reasons of success for npm ๐ŸŒน. ### [](https://basarat.gitbook.io/typescript/index#private-packages) Private packages If you want a private package for your company / team / enterprise you need to sign up to a paid plan, details here : [https://www.npmjs.com/pricing](https://www.npmjs.com/pricing) Of-course you need an account with the right permissions to download a private package. [PreviousCommon Errors](https://basarat.gitbook.io/typescript/main/common-errors) [NextTesting](https://basarat.gitbook.io/typescript/intro-1) Last updated 5 years ago * [Quick common setup](https://basarat.gitbook.io/typescript/index#quick-common-setup) * [Installing a package](https://basarat.gitbook.io/typescript/index#installing-a-package) * [Installing a devDependency](https://basarat.gitbook.io/typescript/index#installing-a-devdependency) * [Security](https://basarat.gitbook.io/typescript/index#security) * [NPM Scripts](https://basarat.gitbook.io/typescript/index#npm-scripts) * [What is with -- in scripts](https://basarat.gitbook.io/typescript/index#what-is-with-in-scripts) * [Public vs. Private packages](https://basarat.gitbook.io/typescript/index#public-vs.-private-packages) * [Public packages](https://basarat.gitbook.io/typescript/index#public-packages) * [Private packages](https://basarat.gitbook.io/typescript/index#private-packages) Copy โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ Low โ”‚ Regular Expression Denial of Service โ”‚ โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค โ”‚ Package โ”‚ debug โ”‚ โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค โ”‚ Dependency of โ”‚ jest [dev] โ”‚ โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค โ”‚ Path โ”‚ jest > jest-cli > istanbul-lib-source-maps > debug โ”‚ โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค โ”‚ More info โ”‚ https://nodesecurity.io/advisories/534 โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ Copy { "scripts": { "build": "tsc -p ." } } Copy { "scripts": { "build": "tsc -p .", "build:watch": "npm run build -- -w" } } Copy { "scripts": { "build": "something --foo", "build:more": "npm run build -- -f -d --bar" } } --- # Husky | TypeScript Deep Dive > Husky can prevent bad commits, pushes and more ๐Ÿถ! If you want to run some JavaScript / TypeScript code before a commit takes place, husky is the tool for that. For example, you can use husky to make sure files are formatted by prettier automatically so you don't have to worry about manually formatting files ever again and focus on the objective of the code instead. Here is the setup: * `npm install husky -D` * Add `scripts` to `package.json`: Copy "precommit": "npm run prettier:write", Now whenever you commit code and there are any formatting changes that need to be made, you'd get them as a _modified_ file in your git log. You can now * If you have pushed your code already, simply commit them with a comment `pretty`. * If you haven't pushed your code, amend your last commit and look like a superhero. [PreviousPrettier](https://basarat.gitbook.io/typescript/intro-2/prettier) [NextESLint](https://basarat.gitbook.io/typescript/intro-2/eslint) Last updated 5 years ago --- # Tools | TypeScript Deep Dive Here are some great tools that I recommend you use or at least try in your TypeScript projects. [PreviousCypress](https://basarat.gitbook.io/typescript/intro-1/cypress) [NextPrettier](https://basarat.gitbook.io/typescript/intro-2/prettier) Last updated 5 years ago --- # Prettier | TypeScript Deep Dive Prettier is a great tool by facebook that makes code formatting so much easier that it's worth mentioning. Setting up with TypeScript using our recommended project setup (aka everything in `src` folder) is super easy: [](https://basarat.gitbook.io/typescript/intro-2/prettier#setup) Setup --------------------------------------------------------------------------- * `npm install prettier -D` * Add `scripts` to `package.json`: Copy "prettier:base": "prettier --parser typescript --single-quote", "prettier:check": "npm run prettier:base -- --list-different \"src/**/*.{ts,tsx}\"", "prettier:write": "npm run prettier:base -- --write \"src/**/*.{ts,tsx}\"" [](https://basarat.gitbook.io/typescript/intro-2/prettier#usage) Usage --------------------------------------------------------------------------- On your build server: * `npm run prettier:check` During dev (or pre commit hook): * `npm run prettier:write` [PreviousTools](https://basarat.gitbook.io/typescript/intro-2) [NextHusky](https://basarat.gitbook.io/typescript/intro-2/husky) Last updated 5 years ago * [Setup](https://basarat.gitbook.io/typescript/intro-2/prettier#setup) * [Usage](https://basarat.gitbook.io/typescript/intro-2/prettier#usage) --- # Non React JSX | TypeScript Deep Dive [![DesignTSX](https://basarat.gitbook.io/typescript/~gitbook/image?url=https%3A%2F%2Fraw.githubusercontent.com%2Fbasarat%2Ftypescript-book%2Fmaster%2Fimages%2Fdesigntsx-banner.png&width=300&dpr=4&quality=100&sign=74c3ed8&sv=2)](https://designtsx.com/) TypeScript provides you with the ability to use something other than React with JSX in a type safe manner. The following lists the customizability points, but note that this is for advanced UI framework authors: * You can disable `react` style emit by using `"jsx" : "preserve"` option. This means that JSX is emitted _as is_ and then you can use your own custom transpiler to transpile the JSX portions. * Using the `JSX` global module: * You can control what HTML tags are available and how they are type checked by customizing the `JSX.IntrinsicElements` interface members. * When using components: * You can control which `class` must be inherited by components by customizing the default `interface ElementClass extends React.Component { }` declaration. * You can control which property is used to type check the attributes (the default is `props`) by customizing the `declare module JSX { interface ElementAttributesProperty { props: {}; } }` declaration. [](https://basarat.gitbook.io/typescript/tsx/others#jsxfactory) `jsxFactory` --------------------------------------------------------------------------------- Passing `--jsxFactory ` along with `--jsx react` allows for using a different JSX factory from the default `React`. The new factory name will be used to call `createElement` functions. ### [](https://basarat.gitbook.io/typescript/tsx/others#example) Example Copy import {jsxFactory} from "jsxFactory"; var div =
Hello JSX!
Compiled with: Results in: [](https://basarat.gitbook.io/typescript/tsx/others#jsx-pragma) `jsx` pragma --------------------------------------------------------------------------------- You can even specify a different `jsxFactory` per file using `jsxPragma` e.g. With `--jsx react` this file will emit to use the factory specfied in the jsx pragma: [PreviousReact](https://basarat.gitbook.io/typescript/tsx/react) [NextOptions](https://basarat.gitbook.io/typescript/intro) Last updated 5 years ago * [jsxFactory](https://basarat.gitbook.io/typescript/tsx/others#jsxfactory) * [Example](https://basarat.gitbook.io/typescript/tsx/others#example) * [jsx pragma](https://basarat.gitbook.io/typescript/tsx/others#jsx-pragma) Copy tsc --jsx react --reactNamespace jsxFactory --m commonJS Copy "use strict"; var jsxFactory_1 = require("jsxFactory"); var div = jsxFactory_1.jsxFactory.createElement("div", null, "Hello JSX!"); Copy /** @jsx jsxFactory */ import {jsxFactory} from "jsxFactory"; var div =
Hello JSX!
Copy "use strict"; var jsxFactory_1 = require("jsxFactory"); var div = jsxFactory_1.jsxFactory.createElement("div", null, "Hello JSX!"); --- # @types | TypeScript Deep Dive [Definitely Typed](https://github.com/DefinitelyTyped/DefinitelyTyped) is definitely one of TypeScript's greatest strengths. The community has effectively gone ahead and **documented** the nature of nearly 90% of the top JavaScript projects out there. This means that you can use these projects in a very interactive and exploratory manner, no need to have the docs open in a separate window and making sure you don't make a typo. [](https://basarat.gitbook.io/typescript/type-system/types#using-types) Using `@types` ------------------------------------------------------------------------------------------- Installation is fairly simple as it just works on top of `npm`. So as an example you can install type definitions for `jquery` simply as: Copy npm install @types/jquery --save-dev `@types` supports both _global_ and _module_ type definitions. ### [](https://basarat.gitbook.io/typescript/type-system/types#global-types) Global `@types` By default any definitions that support global consumption are included automatically. E.g. for `jquery` you should be able to just start using `$` _globally_ in your project. However, for _libraries_ (like `jquery`) I generally recommend using _modules_: ### [](https://basarat.gitbook.io/typescript/type-system/types#module-types) Module `@types` After installation, no special configuration is required really. You just use it like a module e.g.: Copy import * as $ from "jquery"; // Use $ at will in this module :) [](https://basarat.gitbook.io/typescript/type-system/types#controlling-globals) Controlling Globals -------------------------------------------------------------------------------------------------------- As can be seen, having a definition that allows global leak-in automatically can be a problem for some teams. So you can choose to _explicitly_ only bring in the types that make sense using the `tsconfig.json` `compilerOptions.types` e.g.: The above shows a sample where only `jquery` will be allowed to be used. Even if the person installs another definition like `npm install @types/node` its globals (e.g. [`process`](https://nodejs.org/api/process.html) ) will not leak into your code until you add them to the `tsconfig.json` types option. [PreviousJS Migration Guide](https://basarat.gitbook.io/typescript/type-system/migrating) [NextAmbient Declarations](https://basarat.gitbook.io/typescript/type-system/intro) Last updated 5 years ago * [Using @types](https://basarat.gitbook.io/typescript/type-system/types#using-types) * [Global @types](https://basarat.gitbook.io/typescript/type-system/types#global-types) * [Module @types](https://basarat.gitbook.io/typescript/type-system/types#module-types) * [Controlling Globals](https://basarat.gitbook.io/typescript/type-system/types#controlling-globals) Copy { "compilerOptions": { "types" : [\ "jquery"\ ] } } --- # Interpreting Errors | TypeScript Deep Dive Since TypeScript is a heavily focused _Developer Help_ oriented programming language, its errors messages try to be super helpful when something goes wrong. This can lead to a slight information overload for unsuspecting users of compilers that aren't so helpful. Lets look at an example in an IDE to break apart the process of reading an error message. Copy type SomethingComplex = { foo: number, bar: string } function takeSomethingComplex(arg: SomethingComplex) { } function getBar(): string { return 'some bar'; } ////////////////////////////////// // Example error production ////////////////////////////////// const fail = { foo: 123, bar: getBar }; takeSomethingComplex(fail); // TS ERROR HAPPENS HERE This example demonstrates a common programmer error where they _fail_ to call a function (`bar: getBar` should be `bar: getBar()`). Fortunately this mistake is caught by TypeScript as soon as it doesn't meet the type requirements. [](https://basarat.gitbook.io/typescript/main/interpreting-errors#error-categories) Error Categories --------------------------------------------------------------------------------------------------------- There are two categories of TypeScript Error messages (succinct and detailed). ### [](https://basarat.gitbook.io/typescript/main/interpreting-errors#succinct) Succinct The objective of the succinct error message is to provide an example _conventional compiler_ description of the error number and message. For this example the succinct message looks like: It is fairly self explanatory. However, it doesn't provide a deeper breakdown of _why_ the error is happening. That is what the _detailed_ error message is for. ### [](https://basarat.gitbook.io/typescript/main/interpreting-errors#detailed) Detailed For this example the detailed version looks like: The objective of the detailed error message is to _guide_ the user to the reason why some error (type incompatibility in this case) is happening. The first line is same as the succinct, followed by a chain. You should read this chain as a series of responses to the developer question `WHY?` between lines i.e So the root cause is, * for property `bar` * there is a function `() => string` while it was expected as a `string`. This should help the developer fix the bug for the `bar` property (they forgot to invoke `()` the function). [](https://basarat.gitbook.io/typescript/main/interpreting-errors#how-it-shows-up-in-an-ide-tooltip) How it shows up in an IDE Tooltip ------------------------------------------------------------------------------------------------------------------------------------------- The IDE normally shows the `detailed` followed by the `succinct` version in a tooltip as shown below: ![](https://basarat.gitbook.io/typescript/~gitbook/image?url=https%3A%2F%2Fraw.githubusercontent.com%2Fbasarat%2Ftypescript-book%2Fmaster%2Fimages%2Ferrors%2Finterpreting-errors%2Fide.png&width=768&dpr=4&quality=100&sign=49471e00&sv=2) IDE error message example * You normally just read the `detailed` version forming the `WHY?` chain in your head. * You use the succinct version if you want to search for similar errors (using the `TSXXXX` error code or portions of the error message) [PreviousErrors in TypeScript](https://basarat.gitbook.io/typescript/main) [NextCommon Errors](https://basarat.gitbook.io/typescript/main/common-errors) Last updated 5 years ago * [Error Categories](https://basarat.gitbook.io/typescript/main/interpreting-errors#error-categories) * [Succinct](https://basarat.gitbook.io/typescript/main/interpreting-errors#succinct) * [Detailed](https://basarat.gitbook.io/typescript/main/interpreting-errors#detailed) * [How it shows up in an IDE Tooltip](https://basarat.gitbook.io/typescript/main/interpreting-errors#how-it-shows-up-in-an-ide-tooltip) Copy TS2345: Argument of type '{ foo: number; bar: () => string; }' is not assignable to parameter of type 'SomethingComplex'. Copy [ts] Argument of type '{ foo: number; bar: () => string; }' is not assignable to parameter of type 'SomethingComplex'. Types of property 'bar' are incompatible. Type '() => string' is not assignable to type 'string'. Copy ERROR: Argument of type '{ foo: number; bar: () => string; }' is not assignable to parameter of type 'SomethingComplex'. WHY? CAUSE ERROR: Types of property 'bar' are incompatible. WHY? CAUSE ERROR: Type '() => string' is not assignable to type 'string'. --- # Ambient Declarations | TypeScript Deep Dive As we mentioned in [why TypeScript](https://basarat.gitbook.io/typescript/getting-started/why-typescript) : > A major design goal of TypeScript was to make it possible for you to safely and easily use existing JavaScript libraries in TypeScript. TypeScript does this by means of _declaration_. Ambient declarations allow you to _safely use existing popular JavaScript libraries_ and _incrementally migrate your JavaScript/CoffeeScript/Other-Compile-To-Js-Language project to TypeScript_. Studying patterns in ambient declarations for _third party JavaScript code_ is good practice for annotating _your_ TypeScript code base as well. This is why we present it so early on. [Previous@types](https://basarat.gitbook.io/typescript/type-system/types) [NextDeclaration Files](https://basarat.gitbook.io/typescript/type-system/intro/d.ts) Last updated 5 years ago --- # Compilation Context | TypeScript Deep Dive The compilation context is basically just a fancy term for grouping of the files that TypeScript will parse and analyze to determine what is valid and what isn't. Along with the information about which files, the compilation context contains information about _which compiler options_ are in use. A great way to define this logical grouping (we also like to use the term _project_) is using a `tsconfig.json` file. [PreviousProject](https://basarat.gitbook.io/typescript/project) [Nexttsconfig.json](https://basarat.gitbook.io/typescript/project/compilation-context/tsconfig) Last updated 5 years ago --- # Common Errors | TypeScript Deep Dive In this section we explain a number of common error codes that users experience in the real world. [](https://basarat.gitbook.io/typescript/main/common-errors#ts2304) TS2304 ------------------------------------------------------------------------------- Samples: > `Cannot find name ga` `Cannot find name $` `Cannot find module jquery` You are probably using a third party library (e.g. google analytics) and don't have it `declare`d. TypeScript tries to save you from _spelling mistakes_ and _using variables without declaring them_ so you need to be explicit on anything that is _available at runtime_ because of you including some external library ([more on how to fix it](https://basarat.gitbook.io/typescript/type-system/intro/d.ts) ). [](https://basarat.gitbook.io/typescript/main/common-errors#ts2307) TS2307 ------------------------------------------------------------------------------- Samples: > `Cannot find module 'underscore'` You are probably using a third party library (e.g. underscore) as a _module_ ([more on modules](https://basarat.gitbook.io/typescript/project/modules) ) and don't have the ambient declaration file for it ([more on ambient declarations](https://basarat.gitbook.io/typescript/type-system/intro/d.ts) ). [](https://basarat.gitbook.io/typescript/main/common-errors#ts1148) TS1148 ------------------------------------------------------------------------------- Sample: > Cannot compile modules unless the '--module' flag is provided Checkout the [section on modules](https://basarat.gitbook.io/typescript/project/modules) . [](https://basarat.gitbook.io/typescript/main/common-errors#catch-clause-variable-cannot-have-a-type-annotation) Catch clause variable cannot have a type annotation ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Sample: TypeScript is protecting you from JavaScript code in the wild being wrong. Use a type guard instead: [](https://basarat.gitbook.io/typescript/main/common-errors#interface-elementclass-cannot-simultaneously-extend-types-component-and-component) Interface `ElementClass` cannot simultaneously extend types `Component` and `Component` ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- This happens when you have two `react.d.ts` (`@types/react/index.d.ts`) in the compilation context. **Fix**: * Delete `node_modules` and any `package-lock` (or yarn lock) and `npm install` again. * If it doesn't work, find the invalid module (all modules used by your project should have `react.d.ts` as a `peerDependency` and not a hard `dependency`) and report it on their project. [PreviousInterpreting Errors](https://basarat.gitbook.io/typescript/main/interpreting-errors) [NextNPM](https://basarat.gitbook.io/typescript/index) Last updated 5 years ago * [TS2304](https://basarat.gitbook.io/typescript/main/common-errors#ts2304) * [TS2307](https://basarat.gitbook.io/typescript/main/common-errors#ts2307) * [TS1148](https://basarat.gitbook.io/typescript/main/common-errors#ts1148) * [Catch clause variable cannot have a type annotation](https://basarat.gitbook.io/typescript/main/common-errors#catch-clause-variable-cannot-have-a-type-annotation) * [Interface ElementClass cannot simultaneously extend types Component and Component](https://basarat.gitbook.io/typescript/main/common-errors#interface-elementclass-cannot-simultaneously-extend-types-component-and-component) Copy try { something(); } catch (e: Error) { // Catch clause variable cannot have a type annotation } Copy try { something(); } catch (e) { if (e instanceof Error){ // Here you go. } } --- # Interfaces | TypeScript Deep Dive [](https://basarat.gitbook.io/typescript/type-system/interfaces#interfaces) Interfaces ------------------------------------------------------------------------------------------- Interfaces have _zero_ runtime JS impact. There is a lot of power in TypeScript interfaces to declare the structure of variables. The following two are equivalent declarations, the first uses an _inline annotation_, the second uses an _interface_: Copy // Sample A declare var myPoint: { x: number; y: number; }; // Sample B interface Point { x: number; y: number; } declare var myPoint: Point; However, the beauty of _Sample B_ is that if someone authors a library that builds on the `myPoint` library to add new members, they can easily add to the existing declaration of `myPoint`: Copy // Lib a.d.ts interface Point { x: number; y: number; } declare var myPoint: Point; // Lib b.d.ts interface Point { z: number; } // Your code var myPoint.z; // Allowed! This is because **interfaces in TypeScript are open ended**. This is a vital tenet of TypeScript that it allows you to mimic the extensibility of JavaScript using _interfaces_. [](https://basarat.gitbook.io/typescript/type-system/interfaces#classes-can-implement-interfaces) Classes can implement interfaces --------------------------------------------------------------------------------------------------------------------------------------- If you want to use _classes_ that must follow an object structure that someone declared for you in an `interface` you can use the `implements` keyword to ensure compatibility: Basically in the presence of that `implements`, any changes in that external `Point` interface will result in a compile error in your code base so you can easily keep it in sync: Note that `implements` restricts the structure of the class _instances_ i.e.: And stuff like `foo: Point = MyPoint` is not the same thing. [](https://basarat.gitbook.io/typescript/type-system/interfaces#tips) TIPs ------------------------------------------------------------------------------- ### [](https://basarat.gitbook.io/typescript/type-system/interfaces#not-every-interface-is-implementable-easily) Not every interface is implementable easily Interfaces are designed to declare _any arbitrarily crazy_ structure that might be present in JavaScript. Consider the following interface where something is callable with `new`: You would essentially have something like: You can _declare_ all the crazy JS out there with interfaces and even use them safely from TypeScript. Doesn't mean you can use TypeScript classes to implement them. [PreviousVariables](https://basarat.gitbook.io/typescript/type-system/intro/variables) [NextEnums](https://basarat.gitbook.io/typescript/type-system/enums) Last updated 5 years ago * [Interfaces](https://basarat.gitbook.io/typescript/type-system/interfaces#interfaces) * [Classes can implement interfaces](https://basarat.gitbook.io/typescript/type-system/interfaces#classes-can-implement-interfaces) * [TIPs](https://basarat.gitbook.io/typescript/type-system/interfaces#tips) * [Not every interface is implementable easily](https://basarat.gitbook.io/typescript/type-system/interfaces#not-every-interface-is-implementable-easily) Copy interface Point { x: number; y: number; } class MyPoint implements Point { x: number; y: number; // Same as Point } Copy interface Point { x: number; y: number; z: number; // New member } class MyPoint implements Point { // ERROR : missing member `z` x: number; y: number; } Copy var foo: Point = new MyPoint(); Copy interface Crazy { new (): { hello: number }; } Copy class CrazyClass implements Crazy { constructor() { return { hello: 123 }; } } // Because const crazy = new CrazyClass(); // crazy would be {hello:123} --- # Callable | TypeScript Deep Dive You can annotate callables as a part of a type or an interface as follows Copy interface ReturnString { (): string } An instance of such an interface would be a function that returns a string e.g. Copy declare const foo: ReturnString; const bar = foo(); // bar is inferred as a string [](https://basarat.gitbook.io/typescript/type-system/callable#obvious-examples) Obvious examples ----------------------------------------------------------------------------------------------------- Of course such a _callable_ annotation can also specify any arguments / optional arguments / rest arguments as needed. e.g. here is a complex example: Copy interface Complex { (foo: string, bar?: number, ...others: boolean[]): number; } An interface can provide multiple callable annotations to specify function overloading. For example: Copy interface Overloaded { (foo: string): string (foo: number): number } // example implementation function stringOrNumber(foo: number): number; function stringOrNumber(foo: string): string; function stringOrNumber(foo: any): any { if (typeof foo === 'number') { return foo * foo; } else if (typeof foo === 'string') { return `hello ${foo}`; } } const overloaded: Overloaded = stringOrNumber; // example usage const str = overloaded(''); // type of `str` is inferred as `string` const num = overloaded(123); // type of `num` is inferred as `number` Of course, like the body of _any_ interface, you can use the body of a callable interface as a type annotation for a variable. For example: [](https://basarat.gitbook.io/typescript/type-system/callable#arrow-syntax) Arrow Syntax --------------------------------------------------------------------------------------------- To make it easy to specify callable signatures, TypeScript also allows simple arrow type annotations. For example, a function that takes a `number` and returns a `string` can be annotated as: > Only limitation of the arrow syntax: You can't specify overloads. For overloads you must use the full bodied `{ (someArgs): someReturn }` syntax. [](https://basarat.gitbook.io/typescript/type-system/callable#newable) Newable ----------------------------------------------------------------------------------- Newable is just a special type of _callable_ type annotation with the prefix `new`. It simply means that you need to _invoke_ with `new` e.g. [PreviousFunctions](https://basarat.gitbook.io/typescript/type-system/functions) [NextType Assertion](https://basarat.gitbook.io/typescript/type-system/type-assertion) Last updated 5 years ago * [Obvious examples](https://basarat.gitbook.io/typescript/type-system/callable#obvious-examples) * [Arrow Syntax](https://basarat.gitbook.io/typescript/type-system/callable#arrow-syntax) * [Newable](https://basarat.gitbook.io/typescript/type-system/callable#newable) Copy const overloaded: { (foo: string): string (foo: number): number } = (foo: any) => foo; Copy const simple: (foo: number) => string = (foo) => foo.toString(); Copy interface CallMeWithNewToGetString { new(): string } // Usage declare const Foo: CallMeWithNewToGetString; const bar = new Foo(); // bar is inferred to be of type string --- # Namespaces | TypeScript Deep Dive Namespaces provide you with a convenient syntax around a common pattern used in JavaScript: Copy (function(something) { something.foo = 123; })(something || (something = {})) Basically `something || (something = {})` allows an anonymous function `function(something) {}` to _add stuff to an existing object_ (the `something ||` portion) or _start a new object then add stuff to that object_ (the `|| (something = {})` portion). This means that you can have two such blocks split by some execution boundary: Copy (function(something) { something.foo = 123; })(something || (something = {})) console.log(something); // {foo:123} (function(something) { something.bar = 456; })(something || (something = {})) console.log(something); // {foo:123, bar:456} This is commonly used in the JavaScript land for making sure that stuff doesn't leak into the global namespace. With file based modules you don't need to worry about this, but the pattern is still useful for _logical grouping_ of a bunch of functions. Therefore TypeScript provides the `namespace` keyword to group these e.g.: The `namespace` keyword generates the same JavaScript that we saw earlier: One thing to note is that namespaces can be nested so you can do stuff like `namespace Utility.Messaging` to nest a `Messaging` namespace under `Utility`. For most projects we recommend using external modules and using `namespace` for quick demos and porting old JavaScript code. [Previousglobal.d.ts](https://basarat.gitbook.io/typescript/project/modules/globals) [NextDynamic Import Expressions](https://basarat.gitbook.io/typescript/project/dynamic-import-expressions) Last updated 5 years ago Copy namespace Utility { export function log(msg) { console.log(msg); } export function error(msg) { console.error(msg); } } // usage Utility.log('Call me'); Utility.error('maybe!'); Copy (function (Utility) { // Add stuff to Utility })(Utility || (Utility = {})); --- # global.d.ts | TypeScript Deep Dive We discussed _global_ vs. _file_ modules when covering [projects](https://basarat.gitbook.io/typescript/project/modules) and recommended using file based modules and not polluting the global namespace. Nevertheless, if you have beginner TypeScript developers you can give them a `global.d.ts` file to put interfaces / types in the global namespace to make it easy to have some _types_ just _magically_ available for consumption in _all_ your TypeScript code. Another use case for a `global.d.ts` file is to declare compile-time constants that are being injected into the source code by Webpack via the standard [DefinePlugin](https://webpack.js.org/plugins/define-plugin/) plugin. Copy declare const BUILD_MODE_PRODUCTION: boolean; // can be used for conditional compiling declare const BUILD_VERSION: string; > For any code that is going to generate _JavaScript_ we highly recommend using _file modules_, and only use `global.d.ts` to declare compile-time constants and/or to extend standard type declarations declared in `lib.d.ts`. * Bonus: The `global.d.ts` file is also good for quick `declare module "some-library-you-dont-care-to-get-defs-for";` when doing JS to TS migrations. [PreviousFile Module Details](https://basarat.gitbook.io/typescript/project/modules/external-modules) [NextNamespaces](https://basarat.gitbook.io/typescript/project/namespaces) Last updated 5 years ago --- # Declaration Spaces | TypeScript Deep Dive There are two declaration spaces in TypeScript: the _variable_ declaration space and the _type_ declaration space. These concepts are explored below. [](https://basarat.gitbook.io/typescript/project/declarationspaces#type-declaration-space) Type Declaration Space ---------------------------------------------------------------------------------------------------------------------- The type declaration space contains stuff that can be used as a type annotation. E.g. the following are a few type declarations: Copy class Foo {}; interface Bar {}; type Bas = {}; This means that you can use `Foo`, `Bar`, `Bas`, etc. as a type annotation. E.g.: Copy var foo: Foo; var bar: Bar; var bas: Bas; Notice that even though you have `interface Bar`, _you can't use it as a variable_ because it doesn't contribute to the _variable declaration space_. This is shown below: Copy interface Bar {}; var bar = Bar; // ERROR: "cannot find name 'Bar'" The reason why it says `cannot find name` is because the name `Bar` _is not defined_ in the _variable_ declaration space. That brings us to the next topic "Variable Declaration Space". [](https://basarat.gitbook.io/typescript/project/declarationspaces#variable-declaration-space) Variable Declaration Space ------------------------------------------------------------------------------------------------------------------------------ The variable declaration space contains stuff that you can use as a variable. We saw that having `class Foo` contributes a type `Foo` to the _type_ declaration space. Guess what? It also contributes a _variable_ `Foo` to the _variable_ declaration space as shown below: Copy class Foo {}; var someVar = Foo; var someOtherVar = 123; This is great as sometimes you want to pass classes around as variables. Remember that: * we couldn't use something like an `interface` that is _only_ in the _type_ declaration space as a variable. Similarly something that you declare with `var`, is _only_ in the _variable_ declaration space and cannot be used as a type annotation: The reason why it says `cannot find name` is because the name `foo` _is not defined_ in the _type_ declaration space. [PreviousWhich Files?](https://basarat.gitbook.io/typescript/project/compilation-context/files) [NextModules](https://basarat.gitbook.io/typescript/project/modules) Last updated 5 years ago * [Type Declaration Space](https://basarat.gitbook.io/typescript/project/declarationspaces#type-declaration-space) * [Variable Declaration Space](https://basarat.gitbook.io/typescript/project/declarationspaces#variable-declaration-space) Copy var foo = 123; var bar: foo; // ERROR: "cannot find name 'foo'" --- # JS Migration Guide | TypeScript Deep Dive Assuming: * you know JavaScript. * you know patterns and build tools (e.g. webpack) used in the project. With that assumption out of the way, in general the process consists of the following steps: * Add a `tsconfig.json`. * Change your source code file extensions from `.js` to `.ts`. Start _suppressing_ errors using `any`. * Write new code in TypeScript and make as little use of `any` as possible. * Go back to the old code and start adding type annotations and fix identified bugs. * Use ambient definitions for third party JavaScript code. Let us discuss a few of these points further. Note that all JavaScript is _valid_ TypeScript. That is to say that if you give the TypeScript compiler some JavaScript -> the JavaScript emitted by the TypeScript compiler will behave exactly the same as the original JavaScript. This means that changing the extension from `.js` to `.ts` will not adversely affect your codebase. ### [](https://basarat.gitbook.io/typescript/type-system/migrating#suppressing-errors) Suppressing Errors TypeScript will immediately start TypeChecking your code and your original JavaScript code _might not be as neat as you thought it was_ and hence you get diagnostic errors. Many of these errors you can suppress with using `any` e.g.: Copy var foo = 123; var bar = 'hey'; bar = foo; // ERROR: cannot assign a number to a string Even though the **error is valid** (and in most cases the inferred information will be better than what the original authors of different portions of the code bases imagined), your focus will probably be writing new code in TypeScript while progressively updating the old code base. Here you can suppress this error with a type assertion as shown below: In other places you might want to annotate something as `any` e.g.: Suppressed: > Note: Suppressing errors is dangerous, but it allows you to take notice of errors in your _new_ TypeScript code. You might want to leave `// TODO:` comments as you go along.\*\* ### [](https://basarat.gitbook.io/typescript/type-system/migrating#third-party-javascript) Third Party JavaScript You can change your JavaScript to TypeScript, but you can't change the whole world to use TypeScript. This is where TypeScript's ambient definition support comes in. In the beginning we recommend you create a `vendor.d.ts` (the `.d.ts` extension specifies the fact that this is a _declaration file_) and start adding dirty stuff to it. Alternatively create a file specific for the library e.g. `jquery.d.ts` for jquery. > Note: Well maintained and strongly typed definitions for nearly the top 90% JavaScript libraries out there exists in an OSS Repository called [DefinitelyTyped](https://github.com/borisyankov/DefinitelyTyped) > . We recommend looking there before creating your own definitions as we present here. Nevertheless this quick and dirty way is vital knowledge to decrease your initial friction with TypeScript\*\*. Consider the case of `jquery`, you can create a _trivial_ definition for it quite easily: Sometimes you might want to add an explicit annotation on something (e.g. `JQuery`) and you need something in _type declaration space_. You can do that quite easily using the `type` keyword: This provides you an easier future update path. Again, a high quality `jquery.d.ts` exists at [DefinitelyTyped](https://github.com/borisyankov/DefinitelyTyped) . But you now know how to overcome any JavaScript -> TypeScript friction _quickly_ when using third party JavaScript. We will look at ambient declarations in detail next. [](https://basarat.gitbook.io/typescript/type-system/migrating#third-party-npm-modules) Third Party NPM modules -------------------------------------------------------------------------------------------------------------------- Similar to global variable declaration you can declare a global module quite easily. E.g. for `jquery` if you want to use it as a module ([https://www.npmjs.com/package/jquery](https://www.npmjs.com/package/jquery) ) you can write the following yourself: And then you can import it in your file as needed: > Again, a high quality `jquery.d.ts` exists at [DefinitelyTyped](https://github.com/borisyankov/DefinitelyTyped) > that provides a much higher quality jquery module declaration. But it might not exist for your library, so now you have a quick low friction way of continuing the migration ๐ŸŒน [](https://basarat.gitbook.io/typescript/type-system/migrating#external-non-js-resources) External non js resources ------------------------------------------------------------------------------------------------------------------------ You can even allow import of any file e.g. `.css` files (if you are using something like webpack style loaders or css modules) with a simple `*` style declaration (ideally in a [`global.d.ts` file](https://basarat.gitbook.io/typescript/project/modules/globals) ): Now people can `import * as foo from "./some/file.css";` Similarly if you are using html templates (e.g. angular) you can: [](https://basarat.gitbook.io/typescript/type-system/migrating#more) More ------------------------------------------------------------------------------ If you want to be more silent about your upgrade because you couldn't get team buy in to move to TypeScript, [TypeScript has a blog post on upgrading silently without having to convince your team up front](https://devblogs.microsoft.com/typescript/how-to-upgrade-to-typescript-without-anybody-noticing-part-1/) . [PreviousTypeScript's Type System](https://basarat.gitbook.io/typescript/type-system) [Next@types](https://basarat.gitbook.io/typescript/type-system/types) Last updated 5 years ago * [Suppressing Errors](https://basarat.gitbook.io/typescript/type-system/migrating#suppressing-errors) * [Third Party JavaScript](https://basarat.gitbook.io/typescript/type-system/migrating#third-party-javascript) * [Third Party NPM modules](https://basarat.gitbook.io/typescript/type-system/migrating#third-party-npm-modules) * [External non js resources](https://basarat.gitbook.io/typescript/type-system/migrating#external-non-js-resources) * [More](https://basarat.gitbook.io/typescript/type-system/migrating#more) Copy var foo = 123; var bar = 'hey'; bar = foo as any; // Okay! Copy function foo() { return 1; } var bar = 'hey'; bar = foo(); // ERROR: cannot assign a number to a string Copy function foo(): any { // Added `any` return 1; } var bar = 'hey'; bar = foo(); // Okay! Copy declare var $: any; Copy declare type JQuery = any; declare var $: JQuery; Copy declare module "jquery"; Copy import * as $ from "jquery"; Copy declare module "*.css"; Copy declare module "*.html"; --- # Functions | TypeScript Deep Dive * [Parameter Annotations](https://basarat.gitbook.io/typescript/type-system/functions#parameter-annotations) * [Return Type Annotation](https://basarat.gitbook.io/typescript/type-system/functions#return-type-annotation) * [Optional Parameters](https://basarat.gitbook.io/typescript/type-system/functions#optional-parameters) * [Overloading](https://basarat.gitbook.io/typescript/type-system/functions#overloading) [](https://basarat.gitbook.io/typescript/type-system/functions#functions) Functions ---------------------------------------------------------------------------------------- The TypeScript type system pays a lot of love to functions, after all they are the core building blocks of a composable system. ### [](https://basarat.gitbook.io/typescript/type-system/functions#parameter-annotations) Parameter annotations Of course you can annotate function parameters just like you can annotate other variables: Copy // variable annotation var sampleVariable: { bar: number } // function parameter annotation function foo(sampleParameter: { bar: number }) { } Here I used inline type annotations. Of course you can use interfaces etc. ### [](https://basarat.gitbook.io/typescript/type-system/functions#return-type-annotation) Return type annotation You can annotate the return type after the function parameter list with the same style as you use for a variable, e.g. `: Foo` in the below example: Of course I used an `interface` here, but you are free to use other annotations e.g. inline annotations. Quite commonly you don't _need_ to annotate the return type of a function as it can generally be inferred by the compiler. However, it is generally a good idea to add these annotation to help with errors e.g.: If you don't plan to return anything from a function, you can annotate it as `:void`. You can generally drop `:void` and leave it to the inference engine though. ### [](https://basarat.gitbook.io/typescript/type-system/functions#optional-parameters) Optional Parameters You can mark a parameter as optional: Alternatively you can even provide a default value (using `= someValue` after the parameter declaration) which is injected for you if the caller doesn't provide that argument: ### [](https://basarat.gitbook.io/typescript/type-system/functions#overloading) Overloading TypeScript allows you to _declare_ function overloads. This is useful for documentation + type safety purpose. Consider the following code: If you look at the code carefully you realize the meaning of `a`,`b`,`c`,`d` changes based on how many arguments are passed in. Also the function only expects `1`, `2` or `4` arguments. These constraints can be _enforced_ and _documented_ using function overloading. You just declare the function header multiple times. The last function header is the one that is actually active _within_ the function body but is not available to the outside world. This is shown below: Here the first three function headers are available as valid calls to `padding`: Of course it's important for the final declaration (the true declaration as seen from inside the function) to be compatible with all the overloads. This is because that is the true nature of the function calls that the function body needs to account for. > Function overloading in TypeScript doesn't come with any runtime overhead. It just allows you to document the manner you expect the function to be called in and the compiler holds the rest of your code in check. ### [](https://basarat.gitbook.io/typescript/type-system/functions#declaring-functions) Declaring Functions > Quick Tip: _Type Declarations_ are how you describe the types of existing implementations. There are two ways to _declare_ the type of a function without providing an implementation. E.g. The example above are both _exactly_ equivalent. The differences exist when you want to add overloads. You can only add overloads in the long hand declaration version e.g. [Previouslib.d.ts](https://basarat.gitbook.io/typescript/type-system/lib.d.ts) [NextCallable](https://basarat.gitbook.io/typescript/type-system/callable) Last updated 5 years ago * [Functions](https://basarat.gitbook.io/typescript/type-system/functions#functions) * [Parameter annotations](https://basarat.gitbook.io/typescript/type-system/functions#parameter-annotations) * [Return type annotation](https://basarat.gitbook.io/typescript/type-system/functions#return-type-annotation) * [Optional Parameters](https://basarat.gitbook.io/typescript/type-system/functions#optional-parameters) * [Overloading](https://basarat.gitbook.io/typescript/type-system/functions#overloading) * [Declaring Functions](https://basarat.gitbook.io/typescript/type-system/functions#declaring-functions) Copy interface Foo { foo: string; } // Return type annotated as `: Foo` function foo(sample: Foo): Foo { return sample; } Copy interface Foo { foo: string; } function foo(sample: Foo) { return sample; // inferred return type 'Foo' } Copy function foo() { return { fou: 'John Doe' }; // You might not find this misspelling of `foo` till it's too late } sendAsJSON(foo()); Copy function foo(bar: number, bas?: string): void { // .. } foo(123); foo(123, 'hello'); Copy function foo(bar: number, bas: string = 'hello') { console.log(bar, bas); } foo(123); // 123, hello foo(123, 'world'); // 123, world Copy function padding(a: number, b?: number, c?: number, d?: any) { if (b === undefined && c === undefined && d === undefined) { b = c = d = a; } else if (c === undefined && d === undefined) { c = a; d = b; } return { top: a, right: b, bottom: c, left: d }; } Copy // Overloads function padding(all: number); function padding(topAndBottom: number, leftAndRight: number); function padding(top: number, right: number, bottom: number, left: number); // Actual implementation that is a true representation of all the cases the function body needs to handle function padding(a: number, b?: number, c?: number, d?: number) { if (b === undefined && c === undefined && d === undefined) { b = c = d = a; } else if (c === undefined && d === undefined) { c = a; d = b; } return { top: a, right: b, bottom: c, left: d }; } Copy padding(1); // Okay: all padding(1,1); // Okay: topAndBottom, leftAndRight padding(1,1,1,1); // Okay: top, right, bottom, left padding(1,1,1); // Error: Not a part of the available overloads Copy type LongHand = { (a: number): number; }; type ShortHand = (a: number) => number; Copy type LongHandAllowsOverloadDeclarations = { (a: number): number; (a: string): string; }; --- # Type Assertion | TypeScript Deep Dive TypeScript allows you to override its inferred and analyzed view of types in any way you want to. This is done by a mechanism called "type assertion". TypeScript's type assertion is purely you telling the compiler that you know about the types better than it does, and that it should not second guess you. A common use case for type assertion is when you are porting over code from JavaScript to TypeScript. For example consider the following pattern: Copy var foo = {}; foo.bar = 123; // Error: property 'bar' does not exist on `{}` foo.bas = 'hello'; // Error: property 'bas' does not exist on `{}` Here the code errors because the _inferred_ type of `foo` is `{}` i.e. an object with zero properties. Therefore you are not allowed to add `bar` or `bas` to it. You can fix this simply by a type assertion `as Foo`: Copy interface Foo { bar: number; bas: string; } var foo = {} as Foo; foo.bar = 123; foo.bas = 'hello'; [](https://basarat.gitbook.io/typescript/type-system/type-assertion#as-foo-vs.-less-than-foo-greater-than) `as foo` vs. `` ------------------------------------------------------------------------------------------------------------------------------------ Originally the syntax that was added was ``. This is demonstrated below: Copy var foo: any; var bar = foo; // bar is now of type "string" However, there is an ambiguity in the language grammar when using `` style assertions in JSX: Therefore it is now recommended that you just use `as foo` for consistency. [](https://basarat.gitbook.io/typescript/type-system/type-assertion#type-assertion-vs.-casting) Type Assertion vs. Casting ------------------------------------------------------------------------------------------------------------------------------- The reason why it's not called "type casting" is that _casting_ generally implies some sort of runtime support. However, _type assertions_ are purely a compile time construct and a way for you to provide hints to the compiler on how you want your code to be analyzed. [](https://basarat.gitbook.io/typescript/type-system/type-assertion#assertion-considered-harmful) Assertion considered harmful ----------------------------------------------------------------------------------------------------------------------------------- In many cases assertion will allow you to easily migrate legacy code (and even copy paste other code samples into your codebase). However, you should be careful with your use of assertions. Take our original code as a sample, the compiler will not protect you from forgetting to _actually add the properties you promised_: Also another common thought is using an assertion as a means of providing _autocomplete_ e.g.: but the hazard here is the same, if you forget a property the compiler will not complain. It is better if you do the following: In some cases you might need to create a temporary variable, but at least you will not be making (possibly false) promises and instead relying on the type inference to do the checking for you. [](https://basarat.gitbook.io/typescript/type-system/type-assertion#double-assertion) Double assertion ----------------------------------------------------------------------------------------------------------- > [Pro Video Lesson on Double Assertion](https://www.booleanart.com/course/typescript/double-assertion) The type assertion, despite being a bit unsafe as we've shown, is not _completely open season_. E.g. the following is a very valid use case (e.g. the user thinks the event passed in will be a more specific case of an event) and the type assertion works as expected: However, the following is most likely an error and TypeScript will complain as shown despite the user's type assertion: If you _still want that Type, you can use a double assertion_, but first asserting to `unknown` (or `any`) which is compatible with all types and therefore the compiler no longer complains: ### [](https://basarat.gitbook.io/typescript/type-system/type-assertion#how-typescript-determines-if-a-single-assertion-is-not-enough) How TypeScript determines if a single assertion is not enough Basically, the assertion from type `S` to `T` succeeds if either `S` is a subtype of `T` or `T` is a subtype of `S`. This is to provide extra safety when doing type assertions ... completely wild assertions can be very unsafe and you need to use `unknown` (or `any`) to be that unsafe. ### [](https://basarat.gitbook.io/typescript/type-system/type-assertion#as-any-as-vs-as-unknown-as) `as any as` vs `as unknown as` Both are _equally unsafe_ as far as TypeScript is concerned. Use what makes you happy. Considerations: * Linters prefer `unknown` (with `no-explicit-any` rule) * `any` is less characters to type than `unknown` [PreviousCallable](https://basarat.gitbook.io/typescript/type-system/callable) [NextFreshness](https://basarat.gitbook.io/typescript/type-system/freshness) Last updated 1 year ago * [as foo vs. ](https://basarat.gitbook.io/typescript/type-system/type-assertion#as-foo-vs.-less-than-foo-greater-than) * [Type Assertion vs. Casting](https://basarat.gitbook.io/typescript/type-system/type-assertion#type-assertion-vs.-casting) * [Assertion considered harmful](https://basarat.gitbook.io/typescript/type-system/type-assertion#assertion-considered-harmful) * [Double assertion](https://basarat.gitbook.io/typescript/type-system/type-assertion#double-assertion) * [How TypeScript determines if a single assertion is not enough](https://basarat.gitbook.io/typescript/type-system/type-assertion#how-typescript-determines-if-a-single-assertion-is-not-enough) * [as any as vs as unknown as](https://basarat.gitbook.io/typescript/type-system/type-assertion#as-any-as-vs-as-unknown-as) Copy var foo = bar; Copy interface Foo { bar: number; bas: string; } var foo = {} as Foo; // ahhhh .... forget something? Copy interface Foo { bar: number; bas: string; } var foo = { // the compiler will provide autocomplete for properties of Foo // But it is easy for the developer to forget adding all the properties // Also this code is likely to break if Foo gets refactored (e.g. a new property added) }; Copy interface Foo { bar: number; bas: string; } var foo: Foo = { // the compiler will provide autocomplete for properties of Foo }; Copy function handler (event: Event) { let mouseEvent = event as MouseEvent; } Copy function handler(event: Event) { let element = event as HTMLElement; // Error: Neither 'Event' nor type 'HTMLElement' is assignable to the other } Copy function handler(event: Event) { let element = event as unknown as HTMLElement; // Okay! } --- # Freshness | TypeScript Deep Dive * [Freshness](https://basarat.gitbook.io/typescript/type-system/freshness#freshness) * [Allowing extra properties](https://basarat.gitbook.io/typescript/type-system/freshness#allowing-extra-properties) * [Use Case: React](https://basarat.gitbook.io/typescript/type-system/freshness#use-case-react-state) [](https://basarat.gitbook.io/typescript/type-system/freshness#freshness) Freshness ---------------------------------------------------------------------------------------- TypeScript provides a concept of **Freshness** (also called _strict object literal checking_) to make it easier to type check object literals that would otherwise be structurally type compatible. Structural typing is _extremely convenient_. Consider the following piece of code. This allows you to _very conveniently_ upgrade your JavaScript to TypeScript while still preserving a level of type safety: Copy function logName(something: { name: string }) { console.log(something.name); } var person = { name: 'matt', job: 'being awesome' }; var animal = { name: 'cow', diet: 'vegan, but has milk of own species' }; var random = { note: `I don't have a name property` }; logName(person); // okay logName(animal); // okay logName(random); // Error: property `name` is missing However, _structural_ typing has a weakness in that it allows you to misleadingly think that something accepts more data than it actually does. This is demonstrated in the following code which TypeScript will error on as shown: Note that this error _only happens on object literals_. Without this error one might look at the call `logName({ name: 'matt', job: 'being awesome' })` and think that _logName_ would do something useful with `job` where as in reality it will completely ignore it. Another big use case is with interfaces that have optional members, without such object literal checking, a typo would type check just fine. This is demonstrated below: The reason why only object literals are type checked this way is because in this case additional properties _that aren't actually used_ is almost always a typo or a misunderstanding of the API. ### [](https://basarat.gitbook.io/typescript/type-system/freshness#allowing-extra-properties) Allowing extra properties A type can include an index signature to explicitly indicate that excess properties are permitted: ### [](https://basarat.gitbook.io/typescript/type-system/freshness#use-case-react-state) Use Case: React State [Facebook ReactJS](https://facebook.github.io/react/) offers a nice use case for object freshness. Quite commonly in a component you call `setState` with only a few properties instead of passing in all the properties, i.e.: Using the idea of freshness you would mark all the members as optional and _you still get to catch typos_!: [PreviousType Assertion](https://basarat.gitbook.io/typescript/type-system/type-assertion) [NextType Guard](https://basarat.gitbook.io/typescript/type-system/typeguard) Last updated 5 years ago * [Freshness](https://basarat.gitbook.io/typescript/type-system/freshness#freshness) * [Allowing extra properties](https://basarat.gitbook.io/typescript/type-system/freshness#allowing-extra-properties) * [Use Case: React State](https://basarat.gitbook.io/typescript/type-system/freshness#use-case-react-state) Copy function logName(something: { name: string }) { console.log(something.name); } logName({ name: 'matt' }); // okay logName({ name: 'matt', job: 'being awesome' }); // Error: object literals must only specify known properties. `job` is excessive here. Copy function logIfHasName(something: { name?: string }) { if (something.name) { console.log(something.name); } } var person = { name: 'matt', job: 'being awesome' }; var animal = { name: 'cow', diet: 'vegan, but has milk of own species' }; logIfHasName(person); // okay logIfHasName(animal); // okay logIfHasName({neme: 'I just misspelled name to neme'}); // Error: object literals must only specify known properties. `neme` is excessive here. Copy var x: { foo: number, [x: string]: unknown }; x = { foo: 1, baz: 2 }; // Ok, `baz` matched by index signature Copy // Assuming interface State { foo: string; bar: string; } // You want to do: this.setState({foo: "Hello"}); // Error: missing property bar // But because state contains both `foo` and `bar` TypeScript would force you to do: this.setState({foo: "Hello", bar: this.state.bar}); Copy // Assuming interface State { foo?: string; bar?: string; } // You want to do: this.setState({foo: "Hello"}); // Yay works fine! // Because of freshness it's protected against typos as well! this.setState({foos: "Hello"}); // Error: Objects may only specify known properties // And still type checked this.setState({foo: 123}); // Error: Cannot assign number to a string --- # Generics | TypeScript Deep Dive ### [](https://basarat.gitbook.io/typescript/type-system/generics#generics) Generics The key motivation for generics is to document meaningful type dependencies between members. The members can be: * Class instance members * Class methods * function arguments * function return value ### [](https://basarat.gitbook.io/typescript/type-system/generics#motivation-and-samples) Motivation and samples Consider the simple `Queue` (first in, first out) data structure implementation. A simple one in TypeScript / JavaScript looks like: Copy class Queue { private data = []; push(item) { this.data.push(item); } pop() { return this.data.shift(); } } One issue with this implementation is that it allows people to add _anything_ to the queue and when they pop it - it can be _anything_. This is shown below, where someone can push a `string` onto the queue while the usage actually assumes that only `numbers` were pushed in: Copy class Queue { private data = []; push(item) { this.data.push(item); } pop() { return this.data.shift(); } } const queue = new Queue(); queue.push(0); queue.push("1"); // Oops a mistake // a developer walks into a bar console.log(queue.pop().toPrecision(1)); console.log(queue.pop().toPrecision(1)); // RUNTIME ERROR One solution (and in fact the only one in languages that don't support generics) is to go ahead and create _special_ classes just for these constraints. E.g. a quick and dirty number queue: Of course this can quickly become painful e.g. if you want a string queue you have to go through all that effort again. What you really want is a way to say that whatever the type is of the stuff getting _pushed_ it should be the same for whatever gets _popped_. This is done easily with a _generic_ parameter (in this case, at the class level): Another example that we have already seen is that of a _reverse_ function, here the constraint is between what gets passed into the function and what the function returns: In this section you have seen examples of generics being defined _at class level_ and at _function level_. One minor addition worth mentioning is that you can have generics created just for a member function. As a toy example consider the following where we move the `reverse` function into a `Utility` class: > TIP: You can call the generic parameter whatever you want. It is conventional to use `T`, `U`, or `V` when you have simple generics. If you have more than one generic argument try to use meaningful names like `TKey` and `TValue`. The convention is to prefix with `T` because generics are also called _templates_ in other languages like C++. #### [](https://basarat.gitbook.io/typescript/type-system/generics#design-pattern-convenience-generic) Design Pattern: Convenience generic Consider the function: In this case you can see that the type `T` is only used in one place. So there is no constraint _between_ members. This is equivalent to a type assertion in terms of type safety: Generics used _only once_ are no better than an assertion in terms of type safety. That said they do provide _convenience_ to your API. A more obvious example is a function that loads a json response. It returns a promise of _whatever type you pass in_: Note that you still have to explicitly annotate what you want, but the `getJSON` signature `(config) => Promise` saves you a few key strokes (you don't need to annotate the return type of `loadUsers` as it can be inferred): Also `Promise` as a return value is definitely better than alternatives like `Promise`. Another example is where a generic is only used as an argument: Here the generic `T` can be used to annote the type that you want the argument to match e.g. [PreviousReadonly](https://basarat.gitbook.io/typescript/type-system/readonly) [NextType Inference](https://basarat.gitbook.io/typescript/type-system/type-inference) Last updated 4 years ago * [Generics](https://basarat.gitbook.io/typescript/type-system/generics#generics) * [Motivation and samples](https://basarat.gitbook.io/typescript/type-system/generics#motivation-and-samples) Copy class QueueNumber extends Queue { push(item: number) { super.push(item); } pop(): number { return this.data.shift(); } } const queue = new QueueNumber(); queue.push(0); queue.push("1"); // ERROR : cannot push a string. Only numbers allowed // ^ if that error is fixed the rest would be fine too Copy /** A class definition with a generic parameter */ class Queue { private data = []; push(item: T) { this.data.push(item); } pop(): T | undefined { return this.data.shift(); } } /** Again sample usage */ const queue = new Queue(); queue.push(0); queue.push("1"); // ERROR : cannot push a string. Only numbers allowed // ^ if that error is fixed the rest would be fine too Copy function reverse(items: T[]): T[] { var toreturn = []; for (let i = items.length - 1; i >= 0; i--) { toreturn.push(items[i]); } return toreturn; } var sample = [1, 2, 3]; var reversed = reverse(sample); console.log(reversed); // 3,2,1 // Safety! reversed[0] = '1'; // Error! reversed = ['1', '2']; // Error! reversed[0] = 1; // Okay reversed = [1, 2]; // Okay Copy class Utility { reverse(items: T[]): T[] { var toreturn = []; for (let i = items.length - 1; i >= 0; i--) { toreturn.push(items[i]); } return toreturn; } } Copy declare function parse(name: string): T; Copy declare function parse(name: string): any; const something = parse('something') as TypeOfSomething; Copy const getJSON = (config: { url: string, headers?: { [key: string]: string }, }): Promise => { const fetchConfig = ({ method: 'GET', 'Accept': 'application/json', 'Content-Type': 'application/json', ...(config.headers || {}) }); return fetch(config.url, fetchConfig) .then(response => response.json()); } Copy type LoadUsersResponse = { users: { name: string; email: string; }[]; // array of user objects } function loadUsers() { return getJSON({ url: 'https://example.com/users' }); } Copy declare function send(arg: T): void; Copy send({ x:123, // Also you get autocomplete }); // Will TSError if `x:123` does not match the structure expected for Something --- # Literal Types | TypeScript Deep Dive Literals are _exact_ values that are JavaScript primitives. [](https://basarat.gitbook.io/typescript/type-system/literal-types#string-literals) String Literals -------------------------------------------------------------------------------------------------------- You can use a string literal as a type. For example: Copy let foo: 'Hello'; Here we have created a variable called `foo` that _will only allow the literal value_ `_'Hello'_` _to be assigned to it_. This is demonstrated below: Copy let foo: 'Hello'; foo = 'Bar'; // Error: "Bar" is not assignable to type "Hello" They are not very useful on their own but can be combined in a type union to create a powerful (and useful) abstraction e.g.: Copy type CardinalDirection = | "North" | "East" | "South" | "West"; function move(distance: number, direction: CardinalDirection) { // ... } move(1,"North"); // Okay move(1,"Nurth"); // Error! [](https://basarat.gitbook.io/typescript/type-system/literal-types#other-literal-types) Other literal types ---------------------------------------------------------------------------------------------------------------- TypeScript also supports `boolean` and `number` literal types, e.g.: [](https://basarat.gitbook.io/typescript/type-system/literal-types#inference) Inference -------------------------------------------------------------------------------------------- Quite commonly you get an error like `Type string is not assignable to type "foo"`. The following example demonstrates this. This is because `test` is inferred to be of type `{someProp: string}`. The fix here is to use a simple type assertion to tell TypeScript the literal you want it to infer as shown below: or use a type annotation that helps TypeScript infer the correct thing at the point of declaration: [](https://basarat.gitbook.io/typescript/type-system/literal-types#use-cases) Use cases -------------------------------------------------------------------------------------------- Valid use cases for string literal types are: ### [](https://basarat.gitbook.io/typescript/type-system/literal-types#string-based-enums) String based enums [TypeScript enums are number based](https://basarat.gitbook.io/typescript/type-system/enums) . You can use string literals with union types to mock a string based enum as we did in the `CardinalDirection` example above. You can even generate a `Key:Value` structure using the following function: And then generate the literal type union using `keyof typeof`. Here is a complete example: ### [](https://basarat.gitbook.io/typescript/type-system/literal-types#modelling-existing-javascript-apis) Modelling existing JavaScript APIs E.g. [CodeMirror editor has an option `readOnly`](https://codemirror.net/doc/manual.html#option_readOnly) that can either be a `boolean` or the literal string `"nocursor"` (effective valid values `true,false,"nocursor"`). It can be declared as: ### [](https://basarat.gitbook.io/typescript/type-system/literal-types#discriminated-unions) Discriminated Unions We will cover [this later in the book](https://basarat.gitbook.io/typescript/type-system/discriminated-unions) . [PreviousType Guard](https://basarat.gitbook.io/typescript/type-system/typeguard) [NextReadonly](https://basarat.gitbook.io/typescript/type-system/readonly) Last updated 5 years ago * [String Literals](https://basarat.gitbook.io/typescript/type-system/literal-types#string-literals) * [Other literal types](https://basarat.gitbook.io/typescript/type-system/literal-types#other-literal-types) * [Inference](https://basarat.gitbook.io/typescript/type-system/literal-types#inference) * [Use cases](https://basarat.gitbook.io/typescript/type-system/literal-types#use-cases) * [String based enums](https://basarat.gitbook.io/typescript/type-system/literal-types#string-based-enums) * [Modelling existing JavaScript APIs](https://basarat.gitbook.io/typescript/type-system/literal-types#modelling-existing-javascript-apis) * [Discriminated Unions](https://basarat.gitbook.io/typescript/type-system/literal-types#discriminated-unions) Copy type OneToFive = 1 | 2 | 3 | 4 | 5; type Bools = true | false; Copy function iTakeFoo(foo: 'foo') { } const test = { someProp: 'foo' }; iTakeFoo(test.someProp); // Error: Argument of type string is not assignable to parameter of type 'foo' Copy function iTakeFoo(foo: 'foo') { } const test = { someProp: 'foo' as 'foo' }; iTakeFoo(test.someProp); // Okay! Copy function iTakeFoo(foo: 'foo') { } type Test = { someProp: 'foo', } const test: Test = { // Annotate - inferred someProp is always === 'foo' someProp: 'foo' }; iTakeFoo(test.someProp); // Okay! Copy /** Utility function to create a K:V from a list of strings */ function strEnum(o: Array): {[K in T]: K} { return o.reduce((res, key) => { res[key] = key; return res; }, Object.create(null)); } Copy /** Utility function to create a K:V from a list of strings */ function strEnum(o: Array): {[K in T]: K} { return o.reduce((res, key) => { res[key] = key; return res; }, Object.create(null)); } /** * Sample create a string enum */ /** Create a K:V */ const Direction = strEnum([\ 'North',\ 'South',\ 'East',\ 'West'\ ]) /** Create a Type */ type Direction = keyof typeof Direction; /** * Sample using a string enum */ let sample: Direction; sample = Direction.North; // Okay sample = 'North'; // Okay sample = 'AnythingElse'; // ERROR! Copy readOnly: boolean | 'nocursor'; --- # TypeScript's Type System | TypeScript Deep Dive We covered the main features of the TypeScript Type System back when we discussed [Why TypeScript?](https://basarat.gitbook.io/typescript/getting-started/why-typescript) . The following are a few key takeaways from that discussion which don't need further explanation: * The type system in TypeScript is designed to be _optional_ so that _your JavaScript is TypeScript_. * TypeScript does not block _JavaScript emit_ in the presence of Type Errors, allowing you to _progressively update your JS to TS_. Now let's start with the _syntax_ of the TypeScript type system. This way you can start using these annotations in your code immediately and see the benefit. This will prepare you for a deeper dive later. [](https://basarat.gitbook.io/typescript/type-system#basic-annotations) Basic Annotations ---------------------------------------------------------------------------------------------- As mentioned before Types are annotated using `:TypeAnnotation` syntax. Anything that is available in the type declaration space can be used as a Type Annotation. The following example demonstrates type annotations for variables, function parameters and function return values: Copy var num: number = 123; function identity(num: number): number { return num; } ### [](https://basarat.gitbook.io/typescript/type-system#primitive-types) Primitive Types The JavaScript primitive types are well represented in the TypeScript type system. This means `string`, `number`, `boolean` as demonstrated below: Copy var num: number; var str: string; var bool: boolean; num = 123; num = 123.456; num = '123'; // Error str = '123'; str = 123; // Error bool = true; bool = false; bool = 'false'; // Error ### [](https://basarat.gitbook.io/typescript/type-system#arrays) Arrays TypeScript provides dedicated type syntax for arrays to make it easier for you to annotate and document your code. The syntax is basically postfixing `[]` to any valid type annotation (e.g. `:boolean[]`). It allows you to safely do any array manipulation that you would normally do and protects you from errors like assigning a member of the wrong type. This is demonstrated below: ### [](https://basarat.gitbook.io/typescript/type-system#interfaces) Interfaces Interfaces are the core way in TypeScript to compose multiple type annotations into a single named annotation. Consider the following example: Here we've composed the annotations `first: string` + `second: string` into a new annotation `Name` that enforces the type checks on individual members. Interfaces have a lot of power in TypeScript and we will dedicate an entire section to how you can use that to your advantage. ### [](https://basarat.gitbook.io/typescript/type-system#inline-type-annotation) Inline Type Annotation Instead of creating a new `interface` you can annotate anything you want _inline_ using `:{ /*Structure*/ }`. The previous example presented again with an inline type: Inline types are great for quickly providing a one off type annotation for something. It saves you the hassle of coming up with (a potentially bad) type name. However, if you find yourself putting in the same type annotation inline multiple times it's a good idea to consider refactoring it into an interface (or a `type alias` covered later in this section). [](https://basarat.gitbook.io/typescript/type-system#special-types) Special Types -------------------------------------------------------------------------------------- Beyond the primitive types that have been covered there are a few types that have special meaning in TypeScript. These are `any`, `null`, `undefined`, `void`. ### [](https://basarat.gitbook.io/typescript/type-system#any) any The `any` type holds a special place in the TypeScript type system. It gives you an escape hatch from the type system to tell the compiler to bugger off. `any` is compatible with _any and all_ types in the type system. This means that _anything can be assigned to it_ and _it can be assigned to anything_. This is demonstrated in the example below: If you are porting JavaScript code to TypeScript, you are going to be close friends with `any` in the beginning. However, don't take this friendship too seriously as it means that _it is up to you to ensure the type safety_. You are basically telling the compiler to _not do any meaningful static analysis_. ### [](https://basarat.gitbook.io/typescript/type-system#null-and-undefined) `null` and `undefined` How they are treated by the type system depends on the `strictNullChecks` compiler flag (we cover this flag later). When in `strictNullCheck:false`, the `null` and `undefined` JavaScript literals are effectively treated by the type system the same as something of type `any`. These literals can be assigned to any other type. This is demonstrated in the below example: ### [](https://basarat.gitbook.io/typescript/type-system#void) `:void` Use `:void` to signify that a function does not have a return type: [](https://basarat.gitbook.io/typescript/type-system#generics) Generics ---------------------------------------------------------------------------- Many algorithms and data structures in computer science do not depend on the _actual type_ of the object. However, you still want to enforce a constraint between various variables. A simple toy example is a function that takes a list of items and returns a reversed list of items. The constraint here is between what is passed in to the function and what is returned by the function: Here you are basically saying that the function `reverse` takes an array (`items: T[]`) of _some_ type `T` (notice the type parameter in `reverse`) and returns an array of type `T` (notice `: T[]`). Because the `reverse` function returns items of the same type as it takes, TypeScript knows the `reversed` variable is also of type `number[]` and will give you Type safety. Similarly if you pass in an array of `string[]` to the reverse function the returned result is also an array of `string[]` and you get similar type safety as shown below: In fact JavaScript arrays already have a `.reverse` function and TypeScript does indeed use generics to define its structure: This means that you get type safety when calling `.reverse` on any array as shown below: We will discuss more about the `Array` interface later when we present `lib.d.ts` in the section **Ambient Declarations**. [](https://basarat.gitbook.io/typescript/type-system#union-type) Union Type -------------------------------------------------------------------------------- Quite commonly in JavaScript you want to allow a property to be one of multiple types e.g. _a_ `_string_` _or a_ `_number_`. This is where the _union type_ (denoted by `|` in a type annotation e.g. `string|number`) comes in handy. A common use case is a function that can take a single object or an array of the object e.g.: [](https://basarat.gitbook.io/typescript/type-system#intersection-type) Intersection Type ---------------------------------------------------------------------------------------------- `extend` is a very common pattern in JavaScript where you take two objects and create a new one that has the features of both these objects. An **Intersection Type** allows you to use this pattern in a safe way as demonstrated below: [](https://basarat.gitbook.io/typescript/type-system#tuple-type) Tuple Type -------------------------------------------------------------------------------- JavaScript doesn't have first class tuple support. People generally just use an array as a tuple. This is exactly what the TypeScript type system supports. Tuples can be annotated using `: [typeofmember1, typeofmember2]` etc. A tuple can have any number of members. Tuples are demonstrated in the below example: Combine this with the destructuring support in TypeScript, tuples feel fairly first class despite being arrays underneath: [](https://basarat.gitbook.io/typescript/type-system#type-alias) Type Alias -------------------------------------------------------------------------------- TypeScript provides convenient syntax for providing names for type annotations that you would like to use in more than one place. The aliases are created using the `type SomeName = someValidTypeAnnotation` syntax. An example is demonstrated below: Unlike an `interface` you can give a type alias to literally any type annotation (useful for stuff like union and intersection types). Here are a few more examples to make you familiar with the syntax: > TIP: If you need to have hierarchies of Type annotations use an `interface`. They can be used with `implements` and `extends` > > TIP: Use a type alias for simpler object structures (like `Coordinates`) just to give them a semantic name. Also when you want to give semantic names to Union or Intersection types, a Type alias is the way to go. [](https://basarat.gitbook.io/typescript/type-system#summary) Summary -------------------------------------------------------------------------- Now that you can start annotating most of your JavaScript code we can jump into the nitty gritty details of all the power available in TypeScript's Type System. [PreviousLibrary QuickStart](https://basarat.gitbook.io/typescript/library) [NextJS Migration Guide](https://basarat.gitbook.io/typescript/type-system/migrating) Last updated 5 years ago * [Basic Annotations](https://basarat.gitbook.io/typescript/type-system#basic-annotations) * [Primitive Types](https://basarat.gitbook.io/typescript/type-system#primitive-types) * [Arrays](https://basarat.gitbook.io/typescript/type-system#arrays) * [Interfaces](https://basarat.gitbook.io/typescript/type-system#interfaces) * [Inline Type Annotation](https://basarat.gitbook.io/typescript/type-system#inline-type-annotation) * [Special Types](https://basarat.gitbook.io/typescript/type-system#special-types) * [any](https://basarat.gitbook.io/typescript/type-system#any) * [null and undefined](https://basarat.gitbook.io/typescript/type-system#null-and-undefined) * [:void](https://basarat.gitbook.io/typescript/type-system#void) * [Generics](https://basarat.gitbook.io/typescript/type-system#generics) * [Union Type](https://basarat.gitbook.io/typescript/type-system#union-type) * [Intersection Type](https://basarat.gitbook.io/typescript/type-system#intersection-type) * [Tuple Type](https://basarat.gitbook.io/typescript/type-system#tuple-type) * [Type Alias](https://basarat.gitbook.io/typescript/type-system#type-alias) * [Summary](https://basarat.gitbook.io/typescript/type-system#summary) Copy var boolArray: boolean[]; boolArray = [true, false]; console.log(boolArray[0]); // true console.log(boolArray.length); // 2 boolArray[1] = true; boolArray = [false, false]; boolArray[0] = 'false'; // Error! boolArray = 'false'; // Error! boolArray = [true, 'false']; // Error! Copy interface Name { first: string; second: string; } var name: Name; name = { first: 'John', second: 'Doe' }; name = { // Error : `second` is missing first: 'John' }; name = { // Error : `second` is the wrong type first: 'John', second: 1337 }; Copy var name: { first: string; second: string; }; name = { first: 'John', second: 'Doe' }; name = { // Error : `second` is missing first: 'John' }; name = { // Error : `second` is the wrong type first: 'John', second: 1337 }; Copy var power: any; // Takes any and all types power = '123'; power = 123; // Is compatible with all types var num: number; power = num; num = power; Copy var num: number; var str: string; // These literals can be assigned to anything num = null; str = undefined; Copy function log(message): void { console.log(message); } Copy function reverse(items: T[]): T[] { var toreturn = []; for (let i = items.length - 1; i >= 0; i--) { toreturn.push(items[i]); } return toreturn; } var sample = [1, 2, 3]; var reversed = reverse(sample); console.log(reversed); // 3,2,1 // Safety! reversed[0] = '1'; // Error! reversed = ['1', '2']; // Error! reversed[0] = 1; // Okay reversed = [1, 2]; // Okay Copy var strArr = ['1', '2']; var reversedStrs = reverse(strArr); reversedStrs = [1, 2]; // Error! Copy interface Array { reverse(): T[]; // ... } Copy var numArr = [1, 2]; var reversedNums = numArr.reverse(); reversedNums = ['1', '2']; // Error! Copy function formatCommandline(command: string[]|string) { var line = ''; if (typeof command === 'string') { line = command.trim(); } else { line = command.join(' ').trim(); } // Do stuff with line: string } Copy function extend(first: T, second: U): T & U { return { ...first, ...second }; } const x = extend({ a: "hello" }, { b: 42 }); // x now has both `a` and `b` const a = x.a; const b = x.b; Copy var nameNumber: [string, number]; // Okay nameNumber = ['Jenny', 8675309]; // Error! nameNumber = ['Jenny', '867-5309']; Copy var nameNumber: [string, number]; nameNumber = ['Jenny', 8675309]; var [name, num] = nameNumber; Copy type StrOrNum = string|number; // Usage: just like any other notation var sample: StrOrNum; sample = 123; sample = '123'; // Just checking sample = true; // Error! Copy type Text = string | { text: string }; type Coordinates = [number, number]; type Callback = (data: string) => void; --- # Moving Types | TypeScript Deep Dive TypeScript's type system is extremely powerful and allows moving and slicing types in ways not possible in any other single language out there. This is because TypeScript is designed to allow you to work seamlessly with a _highly dynamic_ language like JavaScript. Here we cover a few tricks for moving types around in TypeScript. Key motivation for these : You change one thing and everything else just updates automatically and you get nice errors if something is going to break, like a well designed constraint system. [](https://basarat.gitbook.io/typescript/type-system/moving-types#copying-both-the-type--value) Copying both the Type + Value ---------------------------------------------------------------------------------------------------------------------------------- If you want to move a class around, you might be tempted to do the following: Copy class Foo { } var Bar = Foo; var bar: Bar; // ERROR: cannot find name 'Bar' This is an error because `var` only copied the `Foo` into the _variable_ declaration space and you therefore cannot use `Bar` as a type annotation. The proper way is to use the `import` keyword. Note that you can only use the `import` keyword in such a way if you are using _namespaces_ or _modules_ (more on these later): Copy namespace importing { export class Foo { } } import Bar = importing.Foo; var bar: Bar; // Okay This `import` trick only works for things that are _both type and variable_. [](https://basarat.gitbook.io/typescript/type-system/moving-types#capturing-the-type-of-a-variable) Capturing the type of a variable ----------------------------------------------------------------------------------------------------------------------------------------- You can actually use a variable in a type annotation using the `typeof` operator. This allows you to tell the compiler that one variable is the same type as another. Here is an example to demonstrate this: [](https://basarat.gitbook.io/typescript/type-system/moving-types#capturing-the-type-of-a-class-member) Capturing the type of a class member ------------------------------------------------------------------------------------------------------------------------------------------------- You can traverse into any non-nullable object type to retrieve the type of a property: Alternatively, similar to capturing the type of a variable, you just declare a variable purely for type capturing purposes: [](https://basarat.gitbook.io/typescript/type-system/moving-types#capturing-the-type-of-magic-strings) Capturing the type of magic strings ----------------------------------------------------------------------------------------------------------------------------------------------- Lots of JavaScript libraries and frameworks work off of raw JavaScript strings. You can use `const` variables to capture their type e.g. In this example `bar` has the literal type `"Hello World"`. We cover this more in the [literal type section](https://basarat.gitbook.io/typescript/type-system/literal-types) . [](https://basarat.gitbook.io/typescript/type-system/moving-types#capturing-key-names) Capturing Key Names --------------------------------------------------------------------------------------------------------------- The `keyof` operator lets you capture the key names of a type. E.g. you can use it to capture the key names of a variable by first grabbing its type using `typeof`: This allows you to have stuff like string enums + constants quite easily, as you just saw in the above example. [PreviousIndex Signatures](https://basarat.gitbook.io/typescript/type-system/index-signatures) [NextException Handling](https://basarat.gitbook.io/typescript/type-system/exceptions) Last updated 5 years ago * [Copying both the Type + Value](https://basarat.gitbook.io/typescript/type-system/moving-types#copying-both-the-type--value) * [Capturing the type of a variable](https://basarat.gitbook.io/typescript/type-system/moving-types#capturing-the-type-of-a-variable) * [Capturing the type of a class member](https://basarat.gitbook.io/typescript/type-system/moving-types#capturing-the-type-of-a-class-member) * [Capturing the type of magic strings](https://basarat.gitbook.io/typescript/type-system/moving-types#capturing-the-type-of-magic-strings) * [Capturing Key Names](https://basarat.gitbook.io/typescript/type-system/moving-types#capturing-key-names) Copy var foo = 123; var bar: typeof foo; // `bar` has the same type as `foo` (here `number`) bar = 456; // Okay bar = '789'; // ERROR: Type `string` is not `assignable` to type `number` Copy class Foo { foo: number; // some member whose type we want to capture } let bar: Foo['foo']; // `bar` has type `number` Copy // Purely to capture type declare let _foo: Foo; // Same as before let bar: typeof _foo.foo; // `bar` has type `number` Copy // Capture both the *type* _and_ *value* of magic string: const foo = "Hello World"; // Use the captured type: let bar: typeof foo; // bar can only ever be assigned to `Hello World` bar = "Hello World"; // Okay! bar = "anything else "; // Error! Copy const colors = { red: 'reddish', blue: 'bluish' } type Colors = keyof typeof colors; let color: Colors; // same as let color: "red" | "blue" color = 'red'; // okay color = 'blue'; // okay color = 'anythingElse'; // Error: Type '"anythingElse"' is not assignable to type '"red" | "blue"' --- # Readonly | TypeScript Deep Dive [](https://basarat.gitbook.io/typescript/type-system/readonly#readonly) readonly ------------------------------------------------------------------------------------- TypeScript's type system allows you to mark individual properties on an interface as `readonly`. This allows you to work in a functional way (unexpected mutation is bad): Copy function foo(config: { readonly bar: number, readonly bas: number }) { // .. } let config = { bar: 123, bas: 123 }; foo(config); // You can be sure that `config` isn't changed ๐ŸŒน Of course you can use `readonly` in `interface` and `type` definitions as well e.g.: Copy type Foo = { readonly bar: number; readonly bas: number; } // Initialization is okay let foo: Foo = { bar: 123, bas: 456 }; // Mutation is not foo.bar = 456; // Error: Left-hand side of assignment expression cannot be a constant or a read-only property You can even declare a class property as `readonly`. You can initialize them at the point of declaration or in the constructor as shown below: [](https://basarat.gitbook.io/typescript/type-system/readonly#readonly-1) Readonly --------------------------------------------------------------------------------------- There is a type `Readonly` that takes a type `T` and marks all of its properties as `readonly` using mapped types. Here is a demo that uses it in practice: ### [](https://basarat.gitbook.io/typescript/type-system/readonly#various-use-cases) Various Use Cases #### [](https://basarat.gitbook.io/typescript/type-system/readonly#reactjs) ReactJS One library that loves immutability is ReactJS, you _could_ mark your `Props` and `State` to be immutable e.g.: You do not need to, however, as the type definitions for React mark these as `readonly` already (by internally wrapping the passed in generic types with the `Readonly` type mentioned above). #### [](https://basarat.gitbook.io/typescript/type-system/readonly#seamless-immutable) Seamless Immutable You can even mark index signatures as readonly: This is great if you want to use native JavaScript arrays in an _immutable_ fashion. In fact TypeScript ships with a `ReadonlyArray` interface to allow you to do just that: #### [](https://basarat.gitbook.io/typescript/type-system/readonly#automatic-inference) Automatic Inference In some cases the compiler can automatically infer a particular item to be readonly e.g. within a class if you have a property that only has a getter but no setter, it is assumed readonly e.g.: ### [](https://basarat.gitbook.io/typescript/type-system/readonly#difference-from-const) Difference from `const` `const` 1. is for a variable reference 2. the variable cannot be reassigned to anything else. `readonly` is 1. for a property 2. the property can be modified because of aliasing Sample explaining 1: Sample explaining 2: Basically `readonly` ensures that a property _cannot be modified by me_, but if you give it to someone that doesn't have that guarantee (allowed for type compatibility reasons) they can modify it. Of course if `iMutateFoo` said that they do not mutate `foo.bar` the compiler would correctly flag it as an error as shown: [PreviousLiteral Types](https://basarat.gitbook.io/typescript/type-system/literal-types) [NextGenerics](https://basarat.gitbook.io/typescript/type-system/generics) Last updated 5 years ago * [readonly](https://basarat.gitbook.io/typescript/type-system/readonly#readonly) * [Readonly](https://basarat.gitbook.io/typescript/type-system/readonly#readonly-1) * [Various Use Cases](https://basarat.gitbook.io/typescript/type-system/readonly#various-use-cases) * [Difference from const](https://basarat.gitbook.io/typescript/type-system/readonly#difference-from-const) Copy class Foo { readonly bar = 1; // OK readonly baz: string; constructor() { this.baz = "hello"; // OK } } Copy type Foo = { bar: number; bas: number; } type FooReadonly = Readonly; let foo: Foo = {bar: 123, bas: 456}; let fooReadonly: FooReadonly = {bar: 123, bas: 456}; foo.bar = 456; // Okay fooReadonly.bar = 456; // ERROR: bar is readonly Copy interface Props { readonly foo: number; } interface State { readonly bar: number; } export class Something extends React.Component { someMethod() { // You can rest assured no one is going to do this.props.foo = 123; // ERROR: (props are immutable) this.state.baz = 456; // ERROR: (one should use this.setState) } } Copy export class Something extends React.Component<{ foo: number }, { baz: number }> { // You can rest assured no one is going to do someMethod() { this.props.foo = 123; // ERROR: (props are immutable) this.state.baz = 456; // ERROR: (one should use this.setState) } } Copy /** * Declaration */ interface Foo { readonly[x: number]: number; } /** * Usage */ let foo: Foo = { 0: 123, 2: 345 }; console.log(foo[0]); // Okay (reading) foo[0] = 456; // Error (mutating): Readonly Copy let foo: ReadonlyArray = [1, 2, 3]; console.log(foo[0]); // Okay foo.push(4); // Error: `push` does not exist on ReadonlyArray as it mutates the array foo = foo.concat([4]); // Okay: create a copy Copy class Person { firstName: string = "John"; lastName: string = "Doe"; get fullName() { return this.firstName + this.lastName; } } const person = new Person(); console.log(person.fullName); // John Doe person.fullName = "Dear Reader"; // Error! fullName is readonly Copy const foo = 123; // variable reference var bar: { readonly bar: number; // for property } Copy let foo: { readonly bar: number; } = { bar: 123 }; function iMutateFoo(foo: { bar: number }) { foo.bar = 456; } iMutateFoo(foo); // The foo argument is aliased by the foo parameter console.log(foo.bar); // 456! Copy interface Foo { readonly bar: number; } let foo: Foo = { bar: 123 }; function iTakeFoo(foo: Foo) { foo.bar = 456; // Error! bar is readonly } iTakeFoo(foo); // The foo argument is aliased by the foo parameter --- # Never Type | TypeScript Deep Dive [](https://basarat.gitbook.io/typescript/type-system/never#never) Never ---------------------------------------------------------------------------- > [Professional Lesson on BooleanArt](https://www.booleanart.com/course/typescript/never) > [Youtube: Video lesson on the never type](https://www.youtube.com/watch?v=aldIFYWu6xc) > [Egghead: Video lesson on the never type](https://egghead.io/lessons/typescript-use-the-never-type-to-avoid-code-with-dead-ends-using-typescript) Programming language design does have a concept of _bottom_ type that is a **natural** outcome as soon as you do _code flow analysis_. TypeScript does _code flow analysis_ (๐Ÿ˜Ž) and so it needs to reliably represent stuff that might never happen. The `never` type is used in TypeScript to denote this _bottom_ type. Cases when it occurs naturally: * A function never returns (e.g. if the function body has `while(true){}`) * A function always throws (e.g. in `function foo(){throw new Error('Not Implemented')}` the return type of `foo` is `never`) Of course you can use this annotation yourself as well Copy let foo: never; // Okay However, _only_ `_never_` _can be assigned to another never_. e.g. Copy let foo: never = 123; // Error: Type number is not assignable to never // Okay as the function's return type is `never` let bar: never = (() => { throw new Error(`Throw my hands in the air like I just don't care`) })(); Great. Now let's just jump into its key use case :) [](https://basarat.gitbook.io/typescript/type-system/never#use-case-exhaustive-checks) Use case: Exhaustive Checks ----------------------------------------------------------------------------------------------------------------------- You can call never functions in a never context. And because `never` is only assignable to another `never` you can use it for _compile time_ exhaustive checks as well. This is covered in the [_discriminated union_ section](https://basarat.gitbook.io/typescript/type-system/discriminated-unions) . [](https://basarat.gitbook.io/typescript/type-system/never#confusion-with-void) Confusion with `void` ---------------------------------------------------------------------------------------------------------- As soon as someone tells you that `never` is returned when a function never exits gracefully you intuitively want to think of it as the same as `void`. However, `void` is a Unit. `never` is a falsum. A function that _returns_ nothing returns a Unit `void`. However, a function _that never returns_ (or always throws) returns `never`. `void` is something that can be assigned (without `strictNullChecking`) but `never` can _never_ be assigned to anything other than `never`. [](https://basarat.gitbook.io/typescript/type-system/never#type-inference-in-never-returning-functions) Type inference in never returning functions -------------------------------------------------------------------------------------------------------------------------------------------------------- For function declarations TypeScript infers `void` by default as shown below: Of course you can fix it by an explict annotation: Key reason is backword compatability with real world JavaScript code: If `Base.overrideMe` . > Real world TypeScript can overcome this with `abstract` functions but this inferrence is maintained for compatability. [PreviousType Compatibility](https://basarat.gitbook.io/typescript/type-system/type-compatibility) [NextDiscriminated Unions](https://basarat.gitbook.io/typescript/type-system/discriminated-unions) Last updated 1 year ago * [Never](https://basarat.gitbook.io/typescript/type-system/never#never) * [Use case: Exhaustive Checks](https://basarat.gitbook.io/typescript/type-system/never#use-case-exhaustive-checks) * [Confusion with void](https://basarat.gitbook.io/typescript/type-system/never#confusion-with-void) * [Type inference in never returning functions](https://basarat.gitbook.io/typescript/type-system/never#type-inference-in-never-returning-functions) Copy function foo(x: string | number): boolean { if (typeof x === "string") { return true; } else if (typeof x === "number") { return false; } // Without a never type we would error : // - Not all code paths return a value (strict null checks) // - Or Unreachable code detected // But because TypeScript understands that `fail` function returns `never` // It can allow you to call it as you might be using it for runtime safety / exhaustive checks. return fail("Unexhaustive!"); } function fail(message: string): never { throw new Error(message); } Copy // Inferred return type: void function failDeclaration(message: string) { throw new Error(message); } // Inferred return type: never const failExpression = function(message: string) { throw new Error(message); }; Copy function failDeclaration(message: string): never { throw new Error(message); } Copy class Base { overrideMe() { throw new Error("You forgot to override me!"); } } class Derived extends Base { overrideMe() { // Code that actually returns here } } --- # Type Inference | TypeScript Deep Dive TypeScript can infer (and then check) the type of a variable based on a few simple rules. Because these rules are simple you can train your brain to recognize safe / unsafe code (it happened for me and my teammates quite quickly). > The types flowing is just how I imagine in my brain the flow of type information. [](https://basarat.gitbook.io/typescript/type-system/type-inference#variable-definition) Variable Definition ----------------------------------------------------------------------------------------------------------------- Types of a variable are inferred by definition. Copy let foo = 123; // foo is a `number` let bar = "Hello"; // bar is a `string` foo = bar; // Error: cannot assign `string` to a `number` This is an example of types flowing from right to left. [](https://basarat.gitbook.io/typescript/type-system/type-inference#function-return-types) Function Return Types --------------------------------------------------------------------------------------------------------------------- The return type is inferred by the return statements e.g. the following function is inferred to return a `number`. Copy function add(a: number, b: number) { return a + b; } This is an example of types flowing bottom out. [](https://basarat.gitbook.io/typescript/type-system/type-inference#assignment) Assignment ----------------------------------------------------------------------------------------------- The type of function parameters / return values can also be inferred by assignment e.g. here we say that `foo` is an `Adder`, that makes `number` the type of `a` and `b`. This fact can be demonstrated by the below code which raises an error as you would hope: This is an example of types flowing from left to right. The same _assignment_ style type inference works if you create a function for a callback argument. After all an `argument -> parameter`is just another form of variable assignment. [](https://basarat.gitbook.io/typescript/type-system/type-inference#structuring) Structuring ------------------------------------------------------------------------------------------------- These simple rules also work in the presence of **structuring** (object literal creation). For example in the following case the type of `foo` is inferred to be `{a:number, b:number}` Similarly for arrays: And of course any nesting: [](https://basarat.gitbook.io/typescript/type-system/type-inference#destructuring) Destructuring ----------------------------------------------------------------------------------------------------- And of course, they also work with destructuring, both objects: and arrays: And if the function parameter can be inferred, so can its destructured properties. For example here we destructure the argument into its `a`/`b` members. [](https://basarat.gitbook.io/typescript/type-system/type-inference#type-guards) Type Guards ------------------------------------------------------------------------------------------------- We have already seen how [Type Guards](https://basarat.gitbook.io/typescript/type-system/typeguard) help change and narrow down types (particularly in the case of unions). Type guards are just another form of type inference for a variable in a block. [](https://basarat.gitbook.io/typescript/type-system/type-inference#warnings) Warnings ------------------------------------------------------------------------------------------- ### [](https://basarat.gitbook.io/typescript/type-system/type-inference#be-careful-around-parameters) Be careful around parameters Types do not flow into the function parameters if it cannot be inferred from an assignment. For example in the following case the compiler does not know the type of `foo` so it cannot infer the type of `a` or `b`. However, if `foo` was typed the function parameters type can be inferred (`a`,`b` are both inferred to be of type `number` in the example below). ### [](https://basarat.gitbook.io/typescript/type-system/type-inference#be-careful-around-return) Be careful around return Although TypeScript can generally infer the return type of a function, it might not be what you expect. For example here function `foo` has a return type of `any`. This is because the return type is impacted by the poor type definition for `addOne` (`c` is `any` so the return of `addOne` is `any` so the return of `foo` is `any`). > I find it simplest to always be explicit about function returns. After all, these annotations are a theorem and the function body is the proof. There are other cases that one can imagine, but the good news is that there is a compiler flag that can help catch such bugs. [](https://basarat.gitbook.io/typescript/type-system/type-inference#noimplicitany) `noImplicitAny` ------------------------------------------------------------------------------------------------------- The flag `noImplicitAny` instructs the compiler to raise an error if it cannot infer the type of a variable (and therefore can only have it as an _implicit_ `any` type). You can then * either say that _yes I want it to be of type_ `_any_` by _explicitly_ adding an `: any` type annotation * help the compiler out by adding a few more _correct_ annotations. [PreviousGenerics](https://basarat.gitbook.io/typescript/type-system/generics) [NextType Compatibility](https://basarat.gitbook.io/typescript/type-system/type-compatibility) Last updated 5 years ago * [Variable Definition](https://basarat.gitbook.io/typescript/type-system/type-inference#variable-definition) * [Function Return Types](https://basarat.gitbook.io/typescript/type-system/type-inference#function-return-types) * [Assignment](https://basarat.gitbook.io/typescript/type-system/type-inference#assignment) * [Structuring](https://basarat.gitbook.io/typescript/type-system/type-inference#structuring) * [Destructuring](https://basarat.gitbook.io/typescript/type-system/type-inference#destructuring) * [Type Guards](https://basarat.gitbook.io/typescript/type-system/type-inference#type-guards) * [Warnings](https://basarat.gitbook.io/typescript/type-system/type-inference#warnings) * [Be careful around parameters](https://basarat.gitbook.io/typescript/type-system/type-inference#be-careful-around-parameters) * [Be careful around return](https://basarat.gitbook.io/typescript/type-system/type-inference#be-careful-around-return) * [noImplicitAny](https://basarat.gitbook.io/typescript/type-system/type-inference#noimplicitany) Copy type Adder = (a: number, b: number) => number; let foo: Adder = (a, b) => a + b; Copy type Adder = (a: number, b: number) => number; let foo: Adder = (a, b) => { a = "hello"; // Error: cannot assign `string` to a `number` return a + b; } Copy type Adder = (a: number, b: number) => number; function iTakeAnAdder(adder: Adder) { return adder(1, 2); } iTakeAnAdder((a, b) => { // a = "hello"; // Would Error: cannot assign `string` to a `number` return a + b; }) Copy let foo = { a: 123, b: 456 }; // foo.a = "hello"; // Would Error: cannot assign `string` to a `number` Copy const bar = [1,2,3]; // bar[0] = "hello"; // Would error: cannot assign `string` to a `number` Copy let foo = { bar: [1, 3, 4] }; // foo.bar[0] = 'hello'; // Would error: cannot assign `string` to a `number` Copy let foo = { a: 123, b: 456 }; let {a} = foo; // a = "hello"; // Would Error: cannot assign `string` to a `number` Copy const bar = [1, 2]; let [a, b] = bar; // a = "hello"; // Would Error: cannot assign `string` to a `number` Copy type Adder = (numbers: { a: number, b: number }) => number; function iTakeAnAdder(adder: Adder) { return adder({ a: 1, b: 2 }); } iTakeAnAdder(({a, b}) => { // Types of `a` and `b` are inferred // a = "hello"; // Would Error: cannot assign `string` to a `number` return a + b; }) Copy const foo = (a,b) => { /* do something */ }; Copy type TwoNumberFunction = (a: number, b: number) => void; const foo: TwoNumberFunction = (a, b) => { /* do something */ }; Copy function foo(a: number, b: number) { return a + addOne(b); } // Some external function in a library someone wrote in JavaScript function addOne(c) { return c + 1; } --- # Type Guard | TypeScript Deep Dive * [Type Guard](https://basarat.gitbook.io/typescript/type-system/typeguard#type-guard) * [User Defined Type Guards](https://basarat.gitbook.io/typescript/type-system/typeguard#user-defined-type-guards) [](https://basarat.gitbook.io/typescript/type-system/typeguard#type-guard) Type Guard ------------------------------------------------------------------------------------------ Type Guards allow you to narrow down the type of an object within a conditional block. ### [](https://basarat.gitbook.io/typescript/type-system/typeguard#typeof) typeof TypeScript is aware of the usage of the JavaScript `instanceof` and `typeof` operators. If you use these in a conditional block, TypeScript will understand the type of the variable to be different within that conditional block. Here is a quick example where TypeScript realizes that a particular function does not exist on `string` and points out what was probably a user typo: Copy function doSomething(x: number | string) { if (typeof x === 'string') { // Within the block TypeScript knows that `x` must be a string console.log(x.subtr(1)); // Error, 'subtr' does not exist on `string` console.log(x.substr(1)); // OK } x.substr(1); // Error: There is no guarantee that `x` is a `string` } ### [](https://basarat.gitbook.io/typescript/type-system/typeguard#instanceof) instanceof Here is an example with a class and `instanceof`: Copy class Foo { foo = 123; common = '123'; } class Bar { bar = 123; common = '123'; } function doStuff(arg: Foo | Bar) { if (arg instanceof Foo) { console.log(arg.foo); // OK console.log(arg.bar); // Error! } if (arg instanceof Bar) { console.log(arg.foo); // Error! console.log(arg.bar); // OK } console.log(arg.common); // OK console.log(arg.foo); // Error! console.log(arg.bar); // Error! } doStuff(new Foo()); doStuff(new Bar()); TypeScript even understands `else` so when an `if` narrows out one type it knows that within the else _it's definitely not that type_. Here is an example: ### [](https://basarat.gitbook.io/typescript/type-system/typeguard#in) in The `in` operator does a safe check for the existence of a property on an object and can be used as a type guard. E.g. ### [](https://basarat.gitbook.io/typescript/type-system/typeguard#literal-type-guard) Literal Type Guard You can use `===` / `==` / `!==` / `!=` to distinguish between literal values This even works when you have literal types in a union. You can check the value of a shared property name to discriminate the union e.g. ### [](https://basarat.gitbook.io/typescript/type-system/typeguard#null-and-undefined-with-strictnullchecks) null and undefined with `strictNullChecks` TypeScript is smart enough to rule out both `null` and `undefined` with a `== null` / `!= null` check. For example: ### [](https://basarat.gitbook.io/typescript/type-system/typeguard#user-defined-type-guards) User Defined Type Guards JavaScript doesn't have very rich runtime introspection support built in. When you are using just plain JavaScript Objects (using structural typing to your advantage), you do not even have access to `instanceof` or `typeof`. For these cases you can create _User Defined Type Guard functions_. These are just functions that return `someArgumentName is SomeType`. Here is an example: ### [](https://basarat.gitbook.io/typescript/type-system/typeguard#type-guards-and-callbacks) Type Guards and callbacks TypeScript doesn't assume type guards remain active in callbacks as making this assumption is dangerous. e.g. The fix is as easy as storing the inferred safe value in a local variable, automatically ensuring it doesn't get changed externally, and TypeScript can easily understand that: [PreviousFreshness](https://basarat.gitbook.io/typescript/type-system/freshness) [NextLiteral Types](https://basarat.gitbook.io/typescript/type-system/literal-types) Last updated 5 years ago * [Type Guard](https://basarat.gitbook.io/typescript/type-system/typeguard#type-guard) * [typeof](https://basarat.gitbook.io/typescript/type-system/typeguard#typeof) * [instanceof](https://basarat.gitbook.io/typescript/type-system/typeguard#instanceof) * [in](https://basarat.gitbook.io/typescript/type-system/typeguard#in) * [Literal Type Guard](https://basarat.gitbook.io/typescript/type-system/typeguard#literal-type-guard) * [null and undefined with strictNullChecks](https://basarat.gitbook.io/typescript/type-system/typeguard#null-and-undefined-with-strictnullchecks) * [User Defined Type Guards](https://basarat.gitbook.io/typescript/type-system/typeguard#user-defined-type-guards) * [Type Guards and callbacks](https://basarat.gitbook.io/typescript/type-system/typeguard#type-guards-and-callbacks) Copy class Foo { foo = 123; } class Bar { bar = 123; } function doStuff(arg: Foo | Bar) { if (arg instanceof Foo) { console.log(arg.foo); // OK console.log(arg.bar); // Error! } else { // MUST BE Bar! console.log(arg.foo); // Error! console.log(arg.bar); // OK } } doStuff(new Foo()); doStuff(new Bar()); Copy interface A { x: number; } interface B { y: string; } function doStuff(q: A | B) { if ('x' in q) { // q: A } else { // q: B } } Copy type TriState = 'yes' | 'no' | 'unknown'; function logOutState(state:TriState) { if (state == 'yes') { console.log('User selected yes'); } else if (state == 'no') { console.log('User selected no'); } else { console.log('User has not made a selection yet'); } } Copy type Foo = { kind: 'foo', // Literal type foo: number } type Bar = { kind: 'bar', // Literal type bar: number } function doStuff(arg: Foo | Bar) { if (arg.kind === 'foo') { console.log(arg.foo); // OK console.log(arg.bar); // Error! } else { // MUST BE Bar! console.log(arg.foo); // Error! console.log(arg.bar); // OK } } Copy function foo(a?: number | null) { if (a == null) return; // a is number now. } Copy /** * Just some interfaces */ interface Foo { foo: number; common: string; } interface Bar { bar: number; common: string; } /** * User Defined Type Guard! */ function isFoo(arg: any): arg is Foo { return arg.foo !== undefined; } /** * Sample usage of the User Defined Type Guard */ function doStuff(arg: Foo | Bar) { if (isFoo(arg)) { console.log(arg.foo); // OK console.log(arg.bar); // Error! } else { console.log(arg.foo); // Error! console.log(arg.bar); // OK } } doStuff({ foo: 123, common: '123' }); doStuff({ bar: 123, common: '123' }); Copy // Example Setup declare var foo:{bar?: {baz: string}}; function immediate(callback: ()=>void) { callback(); } // Type Guard if (foo.bar) { console.log(foo.bar.baz); // Okay functionDoingSomeStuff(() => { console.log(foo.bar.baz); // TS error: Object is possibly 'undefined'" }); } Copy // Type Guard if (foo.bar) { console.log(foo.bar.baz); // Okay const bar = foo.bar; functionDoingSomeStuff(() => { console.log(bar.baz); // Okay }); } --- # Enums | TypeScript Deep Dive * [Enums](https://basarat.gitbook.io/typescript/type-system/enums#enums) * [Number Enums and numbers](https://basarat.gitbook.io/typescript/type-system/enums#number-enums-and-numbers) * [Number Enums and strings](https://basarat.gitbook.io/typescript/type-system/enums#number-enums-and-strings) * [Changing the number associated with a number enum](https://basarat.gitbook.io/typescript/type-system/enums#changing-the-number-associated-with-a-number-enum) * [Enums are open ended](https://basarat.gitbook.io/typescript/type-system/enums#enums-are-open-ended) * [Number Enums as flags](https://basarat.gitbook.io/typescript/type-system/enums#number-enums-as-flags) * [String Enums](https://basarat.gitbook.io/typescript/type-system/enums#string-enums) * [Const enums](https://basarat.gitbook.io/typescript/type-system/enums#const-enums) * [Enum with static functions](https://basarat.gitbook.io/typescript/type-system/enums#enum-with-static-functions) [](https://basarat.gitbook.io/typescript/type-system/enums#enums) Enums ---------------------------------------------------------------------------- An enum is a way to organize a collection of related values. Many other programming languages (C/C#/Java) have an `enum` data type but JavaScript does not. However, TypeScript does. Here is an example definition of a TypeScript enum: Copy enum CardSuit { Clubs, Diamonds, Hearts, Spades } // Sample usage var card = CardSuit.Clubs; // Safety card = "not a member of card suit"; // Error : string is not assignable to type `CardSuit` These enums values are `number`s so I'll call them Number Enums from hence forth. ### [](https://basarat.gitbook.io/typescript/type-system/enums#number-enums-and-numbers) Number Enums and Numbers TypeScript enums are number based. This means that numbers can be assigned to an instance of the enum, and so can anything else that is compatible with `number`. ### [](https://basarat.gitbook.io/typescript/type-system/enums#number-enums-and-strings) Number Enums and Strings Before we look further into enums let's look at the JavaScript that it generates, here is a sample TypeScript: generates the following JavaScript: let's focus on the line `Tristate[Tristate["False"] = 0] = "False";`. Within it `Tristate["False"] = 0` should be self explanatory, i.e. sets `"False"` member of `Tristate` variable to be `0`. Note that in JavaScript the assignment operator returns the assigned value (in this case `0`). Therefore the next thing executed by the JavaScript runtime is `Tristate[0] = "False"`. This means that you can use the `Tristate` variable to convert a string version of the enum to a number or a number version of the enum to a string. This is demonstrated below: ### [](https://basarat.gitbook.io/typescript/type-system/enums#changing-the-number-associated-with-a-number-enum) Changing the number associated with a Number Enum By default enums are `0` based and then each subsequent value increments by 1 automatically. As an example consider the following: However, you can change the number associated with any enum member by assigning to it specifically. This is demonstrated below where we start at 3 and start incrementing from there: > TIP: I quite commonly initialize the first enum with `= 1` as it allows me to do a safe truthy check on an enum value. ### [](https://basarat.gitbook.io/typescript/type-system/enums#number-enums-as-flags) Number Enums as flags One excellent use of enums is the ability to use enums as `Flags`. Flags allow you to check if a certain condition from a set of conditions is true. Consider the following example where we have a set of properties about animals: Here we are using the left shift operator to move `1` around a certain level of bits to come up with bitwise disjoint numbers `0001`, `0010`, `0100` and `1000` (these are decimals `1`,`2`,`4`,`8` if you are curious). The bitwise operators `|` (or) / `&` (and) / `~` (not) are your best friends when working with flags and are demonstrated below: Here: * we used `|=` to add flags * a combination of `&=` and `~` to clear a flag * `|` to combine flags > Note: you can combine flags to create convenient shortcuts within the enum definition e.g. `EndangeredFlyingClawedFishEating` below: ### [](https://basarat.gitbook.io/typescript/type-system/enums#string-enums) String Enums We've only looked at enums where the member values are `number`s. You are actually allowed to have enum members with string values as well. e.g. These can be easier to deal with and debug as they provide meaningful / debuggable string values. You can use these values to do simple string comparisons. e.g. ### [](https://basarat.gitbook.io/typescript/type-system/enums#const-enums) Const Enums If you have an enum definition like the following: The line `var lie = Tristate.False` is compiled to the JavaScript `var lie = Tristate.False` (yes, output is same as input). This means that at execution the runtime will need to lookup `Tristate` and then `Tristate.False`. To get a performance boost here you can mark the `enum` as a `const enum`. This is demonstrated below: generates the JavaScript: i.e. the compiler: 1. _Inlines_ any usages of the enum (`0` instead of `Tristate.False`). 2. Does not generate any JavaScript for the enum definition (there is no `Tristate` variable at runtime) as its usages are inlined. #### [](https://basarat.gitbook.io/typescript/type-system/enums#const-enum-preserveconstenums) Const enum preserveConstEnums Inlining has obvious performance benefits. The fact that there is no `Tristate` variable at runtime is simply the compiler helping you out by not generating JavaScript that is not actually used at runtime. However, you might want the compiler to still generate the JavaScript version of the enum definition for stuff like _number to string_ or _string to number_ lookups as we saw. In this case you can use the compiler flag `--preserveConstEnums` and it will still generate the `var Tristate` definition so that you can use `Tristate["False"]` or `Tristate[0]` manually at runtime if you want. This does not impact _inlining_ in any way. [](https://basarat.gitbook.io/typescript/type-system/enums#enum-with-static-functions) Enum with static functions ---------------------------------------------------------------------------------------------------------------------- You can use the declaration `enum` + `namespace` merging to add static methods to an enum. The following demonstrates an example where we add a static member `isBusinessDay` to an enum `Weekday`: ### [](https://basarat.gitbook.io/typescript/type-system/enums#enums-are-open-ended) Enums are open ended > NOTE: open ended enums are only relevant if you are not using modules. You should be using modules. Hence this section is last. Here is the generated JavaScript for an enum shown again: We already explained the `Tristate[Tristate["False"] = 0] = "False";` portion. Now notice the surrounding code `(function (Tristate) { /*code here */ })(Tristate || (Tristate = {}));` specifically the `(Tristate || (Tristate = {}));` portion. This basically captures a local variable `TriState` that will either point to an already defined `Tristate` value or initialize it with a new empty `{}` object. This means that you can split (and extend) an enum definition across multiple files. For example below we have split the definition for `Color` into two blocks Note that you _should_ reinitialize the first member (here `DarkRed = 3`) in a continuation of an enum to get the generated code not clobber values from a previous definition (i.e. the `0`, `1`, ... so on values). TypeScript will warn you if you don't anyways (error message `In an enum with multiple declarations, only one declaration can omit an initializer for its first enum element.`). [PreviousInterfaces](https://basarat.gitbook.io/typescript/type-system/interfaces) [Nextlib.d.ts](https://basarat.gitbook.io/typescript/type-system/lib.d.ts) Last updated 5 years ago * [Enums](https://basarat.gitbook.io/typescript/type-system/enums#enums) * [Number Enums and Numbers](https://basarat.gitbook.io/typescript/type-system/enums#number-enums-and-numbers) * [Number Enums and Strings](https://basarat.gitbook.io/typescript/type-system/enums#number-enums-and-strings) * [Changing the number associated with a Number Enum](https://basarat.gitbook.io/typescript/type-system/enums#changing-the-number-associated-with-a-number-enum) * [Number Enums as flags](https://basarat.gitbook.io/typescript/type-system/enums#number-enums-as-flags) * [String Enums](https://basarat.gitbook.io/typescript/type-system/enums#string-enums) * [Const Enums](https://basarat.gitbook.io/typescript/type-system/enums#const-enums) * [Enum with static functions](https://basarat.gitbook.io/typescript/type-system/enums#enum-with-static-functions) * [Enums are open ended](https://basarat.gitbook.io/typescript/type-system/enums#enums-are-open-ended) Copy enum Color { Red, Green, Blue } var col = Color.Red; col = 0; // Effectively same as Color.Red Copy enum Tristate { False, True, Unknown } Copy var Tristate; (function (Tristate) { Tristate[Tristate["False"] = 0] = "False"; Tristate[Tristate["True"] = 1] = "True"; Tristate[Tristate["Unknown"] = 2] = "Unknown"; })(Tristate || (Tristate = {})); Copy enum Tristate { False, True, Unknown } console.log(Tristate[0]); // "False" console.log(Tristate["False"]); // 0 console.log(Tristate[Tristate.False]); // "False" because `Tristate.False == 0` Copy enum Color { Red, // 0 Green, // 1 Blue // 2 } Copy enum Color { DarkRed = 3, // 3 DarkGreen, // 4 DarkBlue // 5 } Copy enum AnimalFlags { None = 0, HasClaws = 1 << 0, CanFly = 1 << 1, EatsFish = 1 << 2, Endangered = 1 << 3 } Copy enum AnimalFlags { None = 0, HasClaws = 1 << 0, CanFly = 1 << 1, } type Animal = { flags: AnimalFlags } function printAnimalAbilities(animal: Animal) { var animalFlags = animal.flags; if (animalFlags & AnimalFlags.HasClaws) { console.log('animal has claws'); } if (animalFlags & AnimalFlags.CanFly) { console.log('animal can fly'); } if (animalFlags == AnimalFlags.None) { console.log('nothing'); } } let animal: Animal = { flags: AnimalFlags.None }; printAnimalAbilities(animal); // nothing animal.flags |= AnimalFlags.HasClaws; printAnimalAbilities(animal); // animal has claws animal.flags &= ~AnimalFlags.HasClaws; printAnimalAbilities(animal); // nothing animal.flags |= AnimalFlags.HasClaws | AnimalFlags.CanFly; printAnimalAbilities(animal); // animal has claws, animal can fly Copy enum AnimalFlags { None = 0, HasClaws = 1 << 0, CanFly = 1 << 1, EatsFish = 1 << 2, Endangered = 1 << 3, EndangeredFlyingClawedFishEating = HasClaws | CanFly | EatsFish | Endangered, } Copy export enum EvidenceTypeEnum { UNKNOWN = '', PASSPORT_VISA = 'passport_visa', PASSPORT = 'passport', SIGHTED_STUDENT_CARD = 'sighted_tertiary_edu_id', SIGHTED_KEYPASS_CARD = 'sighted_keypass_card', SIGHTED_PROOF_OF_AGE_CARD = 'sighted_proof_of_age_card', } Copy // Where `someStringFromBackend` will be '' | 'passport_visa' | 'passport' ... etc. const value = someStringFromBackend as EvidenceTypeEnum; // Sample use in code if (value === EvidenceTypeEnum.PASSPORT){ console.log('You provided a passport'); console.log(value); // `passport` } Copy enum Tristate { False, True, Unknown } var lie = Tristate.False; Copy const enum Tristate { False, True, Unknown } var lie = Tristate.False; Copy var lie = 0; Copy enum Weekday { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday } namespace Weekday { export function isBusinessDay(day: Weekday) { switch (day) { case Weekday.Saturday: case Weekday.Sunday: return false; default: return true; } } } const mon = Weekday.Monday; const sun = Weekday.Sunday; console.log(Weekday.isBusinessDay(mon)); // true console.log(Weekday.isBusinessDay(sun)); // false Copy var Tristate; (function (Tristate) { Tristate[Tristate["False"] = 0] = "False"; Tristate[Tristate["True"] = 1] = "True"; Tristate[Tristate["Unknown"] = 2] = "Unknown"; })(Tristate || (Tristate = {})); Copy enum Color { Red, Green, Blue } enum Color { DarkRed = 3, DarkGreen, DarkBlue } --- # TypeScript Compiler Internals | TypeScript Deep Dive The TypeScript compiler source is located under the [`src/compiler`](https://github.com/Microsoft/TypeScript/tree/master/src/compiler) folder. It is split into the follow key parts: * Scanner (`scanner.ts`) * Parser (`parser.ts`) * Binder (`binder.ts`) * Checker (`checker.ts`) * Emitter (`emitter.ts`) Each of these get their own unique files in the source. These parts will be explained later on in this chapter. [](https://basarat.gitbook.io/typescript/overview#syntax-vs.-semantics) Syntax vs. Semantics ------------------------------------------------------------------------------------------------- Just because something is _syntactically_ correct doesn't mean it is _semantically_ correct. Consider the following piece of TypeScript code which although _syntactically_ valid is _semantically_ wrong Copy var foo: number = "not a number"; `Semantic` means "meaning" in English. This concept is useful to have in your head. [](https://basarat.gitbook.io/typescript/overview#processing-overview) Processing Overview ----------------------------------------------------------------------------------------------- The following is a quick review of how these key parts of the TypeScript compiler compose: Copy SourceCode ~~ scanner ~~> Token Stream Copy Token Stream ~~ parser ~~> AST `Symbol` is the primary building block of the TypeScript _semantic_ system. As shown the symbols are created as a result of binding. Symbols connect declaration nodes in the AST to other declarations contributing to the same entity. Symbols + AST are what is used by the checker to _semantically_ validate the source code Finally When a JS output is requested: There are a few additional files in the TypeScript compiler that provide utilities to many of these key portions which we cover next. [](https://basarat.gitbook.io/typescript/overview#file-utilities) File: Utilities -------------------------------------------------------------------------------------- `core.ts` : core utilities used by the TypeScript compiler. A few important ones: * `let objectAllocator: ObjectAllocator` : is a variable defined as a singleton global. It provides the definitions for `getNodeConstructor` (Nodes are covered when we look at `parser` / `AST`), `getSymbolConstructor` (Symbols are covered in `binder`), `getTypeConstructor` (Types are covered in `checker`), `getSignatureConstructor` (Signatures are the index, call and construct signatures). [](https://basarat.gitbook.io/typescript/overview#file-key-data-structures) File: Key Data Structures ---------------------------------------------------------------------------------------------------------- `types.ts` contains key data structures and interfaces uses throughout the compiler. Here is a sampling of a few key ones: * `SyntaxKind` The AST node type is identified by the `SyntaxKind` enum. * `TypeChecker` This is the interface provided by the TypeChecker. * `CompilerHost` This is used by the `Program` to interact with the `System`. * `Node` An AST node. [](https://basarat.gitbook.io/typescript/overview#file-system) File: System -------------------------------------------------------------------------------- `system.ts`. All interaction of the TypeScript compiler with the operating system goes through a `System` interface. Both the interface and its implementations (`WScript` and `Node`) are defined in `system.ts`. You can think of it as the _Operating Environment_ (OE). Now that you have an overview of the major files, we can look at the concept of `Program` [PreviousStyleGuide](https://basarat.gitbook.io/typescript/styleguide) [NextProgram](https://basarat.gitbook.io/typescript/overview/program) Last updated 5 years ago * [Syntax vs. Semantics](https://basarat.gitbook.io/typescript/overview#syntax-vs.-semantics) * [Processing Overview](https://basarat.gitbook.io/typescript/overview#processing-overview) * [File: Utilities](https://basarat.gitbook.io/typescript/overview#file-utilities) * [File: Key Data Structures](https://basarat.gitbook.io/typescript/overview#file-key-data-structures) * [File: System](https://basarat.gitbook.io/typescript/overview#file-system) Copy AST ~~ binder ~~> Symbols Copy AST + Symbols ~~ checker ~~> Type Validation Copy AST + Checker ~~ emitter ~~> JS --- # Scanner | TypeScript Deep Dive The source code for the TypeScript scanner is located entirely in `scanner.ts`. Scanner is _controlled_ internally by the `Parser` to convert the source code to an AST. Here is what the desired outcome is. Copy SourceCode ~~ scanner ~~> Token Stream ~~ parser ~~> AST [](https://basarat.gitbook.io/typescript/overview/scanner#usage-by-parser) Usage by Parser ----------------------------------------------------------------------------------------------- There is a _singleton_ `scanner` created in `parser.ts` to avoid the cost of creating scanners over and over again. This scanner is then _primed_ by the parser on demand using the `initializeState` function. Here is a _simplied_ version of the actual code in the parser that you can run demonstrating this concept: `code/compiler/scanner/runScanner.ts` Copy import * as ts from "ntypescript"; // TypeScript has a singleton scanner const scanner = ts.createScanner(ts.ScriptTarget.Latest, /*skipTrivia*/ true); // That is initialized using a function `initializeState` similar to function initializeState(text: string) { scanner.setText(text); scanner.setOnError((message: ts.DiagnosticMessage, length: number) => { console.error(message); }); scanner.setScriptTarget(ts.ScriptTarget.ES5); scanner.setLanguageVariant(ts.LanguageVariant.Standard); } // Sample usage initializeState(` var foo = 123; `.trim()); // Start the scanning var token = scanner.scan(); while (token != ts.SyntaxKind.EndOfFileToken) { console.log(ts.formatSyntaxKind(token)); token = scanner.scan(); } This will print out the following : [](https://basarat.gitbook.io/typescript/overview/scanner#scanner-state) Scanner State ------------------------------------------------------------------------------------------- After you call `scan` the scanner updates its local state (position in the scan, current token details etc). The scanner provides a bunch of utility functions to get the current scanner state. In the below sample we create a scanner and then use it to identify the tokens as well as their positions in the code. `code/compiler/scanner/runScannerWithPosition.ts` This will print out the following: [](https://basarat.gitbook.io/typescript/overview/scanner#standalone-scanner) Standalone scanner ----------------------------------------------------------------------------------------------------- Even though the TypeScript parser has a singleton scanner you can create a standalone scanner using `createScanner` and use its `setText`/`setTextPos` to scan at different points in a file for your amusement. [PreviousTrivia](https://basarat.gitbook.io/typescript/overview/ast/ast-trivia) [NextParser](https://basarat.gitbook.io/typescript/overview/parser) Last updated 5 years ago * [Usage by Parser](https://basarat.gitbook.io/typescript/overview/scanner#usage-by-parser) * [Scanner State](https://basarat.gitbook.io/typescript/overview/scanner#scanner-state) * [Standalone scanner](https://basarat.gitbook.io/typescript/overview/scanner#standalone-scanner) Copy VarKeyword Identifier FirstAssignment FirstLiteralToken SemicolonToken Copy // Sample usage initializeState(` var foo = 123; `.trim()); // Start the scanning var token = scanner.scan(); while (token != ts.SyntaxKind.EndOfFileToken) { let currentToken = ts.formatSyntaxKind(token); let tokenStart = scanner.getStartPos(); token = scanner.scan(); let tokenEnd = scanner.getStartPos(); console.log(currentToken, tokenStart, tokenEnd); } Copy VarKeyword 0 3 Identifier 3 7 FirstAssignment 7 9 FirstLiteralToken 9 13 SemicolonToken 13 14 --- # Mixins | TypeScript Deep Dive TypeScript (and JavaScript) classes support strict single inheritance. So you _cannot_ do: Copy class User extends Tagged, Timestamped { // ERROR : no multiple inheritance } Another way of building up classes from reusable components is to build them by combining simpler partial classes called mixins. The idea is simple, instead of a _class A extending class B_ to get its functionality, _function B takes class A_ and returns a new class with this added functionality. Function `B` is a mixin. > \[A mixin is\] a function that > > 1. takes a constructor, > > 2. creates a class that extends that constructor with new functionality > > 3. returns the new class > A complete example Copy // Needed for all mixins type Constructor = new (...args: any[]) => T; //////////////////// // Example mixins //////////////////// // A mixin that adds a property function Timestamped(Base: TBase) { return class extends Base { timestamp = Date.now(); }; } // a mixin that adds a property and methods function Activatable(Base: TBase) { return class extends Base { isActivated = false; activate() { this.isActivated = true; } deactivate() { this.isActivated = false; } }; } //////////////////// // Usage to compose classes //////////////////// // Simple class class User { name = ''; } // User that is Timestamped const TimestampedUser = Timestamped(User); // User that is Timestamped and Activatable const TimestampedActivatableUser = Timestamped(Activatable(User)); //////////////////// // Using the composed classes //////////////////// const timestampedUserExample = new TimestampedUser(); console.log(timestampedUserExample.timestamp); const timestampedActivatableUserExample = new TimestampedActivatableUser(); console.log(timestampedActivatableUserExample.timestamp); console.log(timestampedActivatableUserExample.isActivated); Let's decompose this example. [](https://basarat.gitbook.io/typescript/type-system/mixins#take-a-constructor) Take a constructor ------------------------------------------------------------------------------------------------------- Mixins take a class and extend it with new functionality. So we need to define what is a _constructor_. Easy as: [](https://basarat.gitbook.io/typescript/type-system/mixins#extend-the-class-and-return-it) Extend the class and return it ------------------------------------------------------------------------------------------------------------------------------- Pretty easy: And that is it ๐ŸŒน [PreviousException Handling](https://basarat.gitbook.io/typescript/type-system/exceptions) [NextJSX](https://basarat.gitbook.io/typescript/tsx) Last updated 5 years ago * [Take a constructor](https://basarat.gitbook.io/typescript/type-system/mixins#take-a-constructor) * [Extend the class and return it](https://basarat.gitbook.io/typescript/type-system/mixins#extend-the-class-and-return-it) Copy // Needed for all mixins type Constructor = new (...args: any[]) => T; Copy // A mixin that adds a property function Timestamped(Base: TBase) { return class extends Base { timestamp = Date.now(); }; } --- # TIP: SyntaxKind enum | TypeScript Deep Dive `SyntaxKind` is defined as a `const enum`, here is a sample: Copy export const enum SyntaxKind { Unknown, EndOfFileToken, SingleLineCommentTrivia, // ... LOTS more It's a `const enum` (a concept [we covered previously](https://basarat.gitbook.io/typescript/type-system/enums) ) so that it gets _inlined_ (e.g. `ts.SyntaxKind.EndOfFileToken` becomes `1`) and we don't get a dereferencing cost when working with the AST. However, the compiler is compiled with `--preserveConstEnums` compiler flag so that the enum _is still available at runtime_. So in JavaScript you can use `ts.SyntaxKind.EndOfFileToken` if you want. Additionally you can convert these enum members to display strings using the following function: Copy export function syntaxKindToName(kind: ts.SyntaxKind) { return (ts).SyntaxKind[kind]; } [PreviousTIP: Visit Children](https://basarat.gitbook.io/typescript/overview/ast/ast-tip-children) [NextTrivia](https://basarat.gitbook.io/typescript/overview/ast/ast-trivia) Last updated 5 years ago --- # Parser | TypeScript Deep Dive The sourcecode for the TypeScript parser is located entirely in `parser.ts`. Scanner is _controlled_ internally by the `Parser` to convert the source code to an AST. Here is a review of what the desired outcome is. Copy SourceCode ~~ scanner ~~> Token Stream ~~ parser ~~> AST The parser is implemented as a singleton (similar reasons to `scanner`, don't want to recreate it if we can reinit it). It is actually implemented as `namespace Parser` which contains _state_ variables for the Parser as well as a singleton `scanner`. As mentioned before it contains a `const scanner`. The parser functions manage this scanner. [](https://basarat.gitbook.io/typescript/overview/parser#usage-by-program) Usage by program ------------------------------------------------------------------------------------------------ Parser is driven indirectly by Program (indirectly as its actually by `CompilerHost` which we mentioned previously). Basically this is the simplified call stack: Copy Program -> CompilerHost.getSourceFile -> (global function parser.ts).createSourceFile -> Parser.parseSourceFile The `parseSourceFile` not only primes the state for the Parser but also primes the state for the `scanner` by calling `initializeState`. It then goes on to parse the source file using `parseSourceFileWorker`. [](https://basarat.gitbook.io/typescript/overview/parser#sample-usage) Sample Usage ---------------------------------------------------------------------------------------- Before we dig too deep into the parser internals, here is a sample code that uses the TypeScript's parser to get the AST of a source file (using `ts.createSourceFile`), and then print it. `code/compiler/parser/runParser.ts` Copy import * as ts from "ntypescript"; function printAllChildren(node: ts.Node, depth = 0) { console.log(new Array(depth + 1).join('----'), ts.formatSyntaxKind(node.kind), node.pos, node.end); depth++; node.getChildren().forEach(c=> printAllChildren(c, depth)); } var sourceCode = ` var foo = 123; `.trim(); var sourceFile = ts.createSourceFile('foo.ts', sourceCode, ts.ScriptTarget.ES5, true); printAllChildren(sourceFile); This will print out the following: This looks like a (very right sided) tree if you tilt your head to the left. [PreviousScanner](https://basarat.gitbook.io/typescript/overview/scanner) [NextParser Functions](https://basarat.gitbook.io/typescript/overview/parser/parser-functions) Last updated 5 years ago * [Usage by program](https://basarat.gitbook.io/typescript/overview/parser#usage-by-program) * [Sample Usage](https://basarat.gitbook.io/typescript/overview/parser#sample-usage) Copy SourceFile 0 14 ---- SyntaxList 0 14 -------- VariableStatement 0 14 ------------ VariableDeclarationList 0 13 ---------------- VarKeyword 0 3 ---------------- SyntaxList 3 13 -------------------- VariableDeclaration 3 13 ------------------------ Identifier 3 7 ------------------------ FirstAssignment 7 9 ------------------------ FirstLiteralToken 9 13 ------------ SemicolonToken 13 14 ---- EndOfFileToken 14 14 --- # Cypress | TypeScript Deep Dive Cypress is a great E2E testing tool. Here are a few great reasons to consider it: * Isolated installation possible. * Ships with TypeScript support out of the box. * Provides a nice interactive google chrome debug experience. This is very similar to how UI devs mostly work manually. * Has command - execution separation which allows for more powerful debugging and test stability (more on this below). * Has implicit assertions to provide more meaningful debug experience with less brittle tests (more on this in the tips below). * Provides the ability to mock out and observe backend XHRs easily without changing your application code (more on this in the tips below). [](https://basarat.gitbook.io/typescript/intro-1/cypress#installation) Installation ---------------------------------------------------------------------------------------- The steps provided in this installation process will give you a nice `e2e` folder that you can copy/paste or as boiler plate for your organization. > Same steps presented in a video format over at my [youtube channel](https://www.youtube.com/watch?v=n3SvvZSWwfM) > . Create an e2e directory, install cypress, TypeScript and setup the typescript and cypress config files: Copy mkdir e2e cd e2e npm init -y npm install cypress typescript npx tsc --init --types cypress --lib dom,es6 echo {} > cypress.json > Here are a few reasons for creating a separate `e2e` folder especially for cypress: > > * Creating a separate directory or `e2e` makes it easier to isolate its `package.json` dependencies from the rest of your project. This results in less dependency conflicts. > > * Testing frameworks have a habit of polluting the global namespace with stuff like `describe` `it` `expect`. It is best to keep the e2e `tsconfig.json` and `node_modules` in this special `e2e` folder to prevent global type definition conflicts. > Add a few scripts to the `e2e/package.json` file: Write your first test under `cypress/integration/basic.ts`: Now run `npm run cypress:open` during development and `npm run cypress:run` on your build server ๐ŸŒน [](https://basarat.gitbook.io/typescript/intro-1/cypress#more-description-of-key-files) More description of key Files -------------------------------------------------------------------------------------------------------------------------- Under the `e2e` folder you now have these files: * `/cypress.json`: Configure cypress. The default is empty and that is all you need. * `/cypress` Subfolders: * `/integration`: All your tests. * Feel free to create tests under subfolders for better organization e.g. `/someFeatureFolder/something.spec.ts`. [](https://basarat.gitbook.io/typescript/intro-1/cypress#first-test) First test ------------------------------------------------------------------------------------ * create a file `/cypress/integration/first.ts` with the following contents: [](https://basarat.gitbook.io/typescript/intro-1/cypress#running-in-development) Running in development ------------------------------------------------------------------------------------------------------------ Open the cypress IDE using the following command. And select a test to run. [](https://basarat.gitbook.io/typescript/intro-1/cypress#running-on-a-build-server) Running on a build server ------------------------------------------------------------------------------------------------------------------ You can run cypress tests in ci mode using the following command. [](https://basarat.gitbook.io/typescript/intro-1/cypress#tip-sharing-code-between-ui-and-test) Tip: Sharing code between UI and test ----------------------------------------------------------------------------------------------------------------------------------------- Cypress tests are compiled / packed and run in the browser. So feel free to import any project code into your test. For example you can share Id values between UI and Tests to make sure the CSS selectors don't break: [](https://basarat.gitbook.io/typescript/intro-1/cypress#tip-creating-page-objects) Tip: Creating Page Objects ------------------------------------------------------------------------------------------------------------------- Creating objects that provide a convenient handle for all the interactions that various tests need to do with a page is a common testing convention. You can create page objects using TypeScript classes with getters and methods e.g. [](https://basarat.gitbook.io/typescript/intro-1/cypress#tip-explicit-assertion) Tip: Explicit assertion ------------------------------------------------------------------------------------------------------------- Cypress ships with (built in) chai and chai-query assertion libraries to help testing webpages. You use them with `.should` command passing in the chainer as a string, replacing `.to.foo` with `should('foo')` e.g. with chai-jquery you would `expect($(#foo)).to.have.text('something')`, with cypress you would `cy.get('#foo').should('have.text', 'something')`: > You get intellisense for `should` chainers as cypress ships with correct TypeScript definitions ๐Ÿ‘๐Ÿป The complete list of chainers is available here : [https://docs.cypress.io/guides/references/assertions.html](https://docs.cypress.io/guides/references/assertions.html) If you want something complex you can even use `should(callback)` and e.g. > TIP: cypress with do automatic retries on the callback as well, so they are just as flake free as standard string chainers. [](https://basarat.gitbook.io/typescript/intro-1/cypress#tip-commands-and-chaining) Tip: Commands and Chaining ------------------------------------------------------------------------------------------------------------------- Every function call in a cypress chain is a `command`. The `should` command is an assertion. It is conventional to start distinct _category_ of chains and actions separately e.g. Some other libraries _evaluate and run_ the code at the same time. Those libraries force you to have a single chain which can be nightmare to debug with selectors and assertions mingled in. Cypress commands are essentially _declarations_ to the cypress runtime to execute the commands later. Simple words: Cypress makes it easier. [](https://basarat.gitbook.io/typescript/intro-1/cypress#tip-using-contains-for-easier-querying) Tip: Using `contains` for easier querying ----------------------------------------------------------------------------------------------------------------------------------------------- The following shows an example: [](https://basarat.gitbook.io/typescript/intro-1/cypress#tip-smart-delays-and-retries) Tip: Smart delays and retries ------------------------------------------------------------------------------------------------------------------------- Cypress will automatically wait (and retry) for many async things e.g. This keeps you from having to constantly add arbitrary timeout (and retry) logic in your test code flow. [](https://basarat.gitbook.io/typescript/intro-1/cypress#tip-implicit-assertion) Tip: Implicit assertion ------------------------------------------------------------------------------------------------------------- Cypress has a concept of implicit assertion. These kick in if a future command is erroring because of a previous command. E.g. the following will error at `contains` (after automatic retries of course) as nothing found can get `click`ed: In traditional frameworks you would get a horrible error like `click` doesn't exist on `null`. In Cypress you get a nice error `#foo` does not contain `Submit`. This error is a form of an implicit assertion. [](https://basarat.gitbook.io/typescript/intro-1/cypress#tip-waiting-for-an-http-request) Tip: Waiting for an HTTP request ------------------------------------------------------------------------------------------------------------------------------- A lot of tests have been traditionally brittle due to all the arbitrary timeouts needed for XHRs that an application makes. `cy.server` makes it easy to * create an alias for backend calls * wait for them to occur e.g. [](https://basarat.gitbook.io/typescript/intro-1/cypress#tip-mocking-an-http-request-response) Tip: Mocking an HTTP request response ----------------------------------------------------------------------------------------------------------------------------------------- You can also easily mock out a request response using `route`: ### [](https://basarat.gitbook.io/typescript/intro-1/cypress#tip-asserting-an-http-request-response) Tip: Asserting an Http request response You can assert requests without mocking using `route` `onRequest` / `onResponse` e.g. [](https://basarat.gitbook.io/typescript/intro-1/cypress#tip-mocking-time) Tip: Mocking time ------------------------------------------------------------------------------------------------- You can use `wait` to pause a test for some time e.g. to test an automatic "you are about to be logged out" notification screen: However, it is recommended to mock time using `cy.clock` and forwarding time using `cy.tick` e.g. [](https://basarat.gitbook.io/typescript/intro-1/cypress#tip-unit-testing-application-code) Tip: Unit testing application code ----------------------------------------------------------------------------------------------------------------------------------- You can also use cypress to unit test your application code in isolation e.g. [](https://basarat.gitbook.io/typescript/intro-1/cypress#tip-mocking-in-unit-testing) Tip: Mocking in unit testing ----------------------------------------------------------------------------------------------------------------------- If you are unit testing modules in your application you can provide mocks using `cy.stub` e.g. if you want to ensure that `navigate` is called in a function `foo`: * `foo.ts` * You can do this as in `some.spec.ts`: [](https://basarat.gitbook.io/typescript/intro-1/cypress#tip-command-execution-separation) Tip: Command - execution separation ----------------------------------------------------------------------------------------------------------------------------------- When you invoke a cypress command (or assertion) e.g. `cy.get('#something')`, the function immediately returns without actually carrying out the action. What it does do, is informs the cypress test runner that you will need to carry out (execute) an action (in this case a `get`) at some point. You are basically building a command list that the runner will then go ahead and execute. You can verify this command - execution separation with a simple test, observe that you will see the `start / between / end` `console.log` statements execute immediately before the runner starts _executing_ the commands: This command execution separation has two big benefits: * The runner can execute the commands in a _flake resistant_ manner with automatic retries and implicit assertions. * Allows you to write asynchronous code in a synchronous fashion without having to do a constant _chaining_ which results in difficult to maintain code. [](https://basarat.gitbook.io/typescript/intro-1/cypress#tip-breakpoint) Tip: Breakpoint --------------------------------------------------------------------------------------------- The automatic snapshots + command log generated by the cypress test are great for debugging. That said you can pause test execution if you want. First make sure you have chrome developer tools (lovingly called dev tools) open in the test runner (`CMD + ALT + i` on mac / `F12` on windows). Once the dev tools are open you can re-run the test and the dev tools will stay open. If you have the dev tools open, you can pause test execution in two ways: * Application code breakpoints: Use a `debugger` statement in your application code and the test runner will stop on that just like standard web development. * Test code breakpoints: You can use the `.debug()` command and cypress test execution will stop at it. Alternatively you can use a `debugger` statement in a `.then` command callback to cause a pause. e.g `.then(() => { debugger })`. You can even use it to grab some element `cy.get('#foo').then(($ /* a reference to the dom element */) => { debugger; })` or a network call e.g. `cy.request('https://someurl').then((res /* network response */) => { debugger });`. However idiomatic way is `cy.get('#foo').debug()` and then when the test runner is paused on `debug` you can click on the `get` in the command log to automatically `console.log` any information you might need about the `.get('#foo')` command (and similarly for any other commands you want to debug). [](https://basarat.gitbook.io/typescript/intro-1/cypress#tip-start-server-and-test) Tip: Start server and test ------------------------------------------------------------------------------------------------------------------- If you need to start a local server before your tests can run you can add `start-server-and-test` [https://github.com/bahmutov/start-server-and-test](https://github.com/bahmutov/start-server-and-test) as a dependency. It takes the following arguments * an npm script to _run_ the server (aka server) * an endpoint to check if the server has booted up (aka start) * an npm script to initiate the testing (aka test) Example package.json: [](https://basarat.gitbook.io/typescript/intro-1/cypress#resources) Resources ---------------------------------------------------------------------------------- * Website: [https://www.cypress.io/](https://www.cypress.io/) * Write your first cypress test (gives a nice tour of the cypress IDE) : [https://docs.cypress.io/guides/getting-started/writing-your-first-test.html](https://docs.cypress.io/guides/getting-started/writing-your-first-test.html) * Setting up a CI environment (e.g. the provided docker image that works out of the box with `cypress run`): [https://docs.cypress.io/guides/guides/continuous-integration.html](https://docs.cypress.io/guides/guides/continuous-integration.html) * Recipes (Lists recipes with descriptions. Click on headings to navigate to the source code for the recipe): [https://docs.cypress.io/examples/examples/recipes.html](https://docs.cypress.io/examples/examples/recipes.html) * Visual Testing : [https://docs.cypress.io/guides/tooling/visual-testing.html](https://docs.cypress.io/guides/tooling/visual-testing.html) * Optionally set a `baseUrl` in cypress.json to [prevent an initial reload that happens after first `visit`.](https://github.com/cypress-io/cypress/issues/2542) * Code coverage with cypress: [Webcast](https://www.youtube.com/watch?v=C8g5X4vCZJA) [PreviousJest](https://basarat.gitbook.io/typescript/intro-1/jest) [NextTools](https://basarat.gitbook.io/typescript/intro-2) Last updated 5 years ago * [Installation](https://basarat.gitbook.io/typescript/intro-1/cypress#installation) * [More description of key Files](https://basarat.gitbook.io/typescript/intro-1/cypress#more-description-of-key-files) * [First test](https://basarat.gitbook.io/typescript/intro-1/cypress#first-test) * [Running in development](https://basarat.gitbook.io/typescript/intro-1/cypress#running-in-development) * [Running on a build server](https://basarat.gitbook.io/typescript/intro-1/cypress#running-on-a-build-server) * [Tip: Sharing code between UI and test](https://basarat.gitbook.io/typescript/intro-1/cypress#tip-sharing-code-between-ui-and-test) * [Tip: Creating Page Objects](https://basarat.gitbook.io/typescript/intro-1/cypress#tip-creating-page-objects) * [Tip: Explicit assertion](https://basarat.gitbook.io/typescript/intro-1/cypress#tip-explicit-assertion) * [Tip: Commands and Chaining](https://basarat.gitbook.io/typescript/intro-1/cypress#tip-commands-and-chaining) * [Tip: Using contains for easier querying](https://basarat.gitbook.io/typescript/intro-1/cypress#tip-using-contains-for-easier-querying) * [Tip: Smart delays and retries](https://basarat.gitbook.io/typescript/intro-1/cypress#tip-smart-delays-and-retries) * [Tip: Implicit assertion](https://basarat.gitbook.io/typescript/intro-1/cypress#tip-implicit-assertion) * [Tip: Waiting for an HTTP request](https://basarat.gitbook.io/typescript/intro-1/cypress#tip-waiting-for-an-http-request) * [Tip: Mocking an HTTP request response](https://basarat.gitbook.io/typescript/intro-1/cypress#tip-mocking-an-http-request-response) * [Tip: Asserting an Http request response](https://basarat.gitbook.io/typescript/intro-1/cypress#tip-asserting-an-http-request-response) * [Tip: Mocking time](https://basarat.gitbook.io/typescript/intro-1/cypress#tip-mocking-time) * [Tip: Unit testing application code](https://basarat.gitbook.io/typescript/intro-1/cypress#tip-unit-testing-application-code) * [Tip: Mocking in unit testing](https://basarat.gitbook.io/typescript/intro-1/cypress#tip-mocking-in-unit-testing) * [Tip: Command - execution separation](https://basarat.gitbook.io/typescript/intro-1/cypress#tip-command-execution-separation) * [Tip: Breakpoint](https://basarat.gitbook.io/typescript/intro-1/cypress#tip-breakpoint) * [Tip: Start server and test](https://basarat.gitbook.io/typescript/intro-1/cypress#tip-start-server-and-test) * [Resources](https://basarat.gitbook.io/typescript/intro-1/cypress#resources) Copy "scripts": { "cypress:open": "cypress open", "cypress:run": "cypress run" }, Copy it('should perform basic google search', () => { cy.visit('https://google.com'); cy.get('[name="q"]') .type('subscribe') .type('{enter}'); }); Copy describe('google search', () => { it('should work', () => { cy.visit('http://www.google.com'); cy.get('#lst-ib').type('Hello world{enter}') }); }); Copy npm run cypress:open Copy npm run cypress:run Copy import { Ids } from '../../../src/app/constants'; // Later cy.get(`#${Ids.username}`) .type('john') Copy import { Ids } from '../../../src/app/constants'; class LoginPage { visit() { cy.visit('/login'); } get username() { return cy.get(`#${Ids.username}`); } } const page = new LoginPage(); // Later page.visit(); page.username.type('john'); Copy cy.get('#foo') .should('have.text', 'something') Copy cy.get('div') .should(($div) => { expect($div).to.have.length(1); expect($div[0].className).to.contain('heading'); }) // This is just an example. Normally you would `.should('have.class', 'heading') Copy // Don't do this cy.get(/**something*/) .should(/**something*/) .click() .should(/**something*/) .get(/**something else*/) .should(/**something*/) // Prefer separating the two gets cy.get(/**something*/) .should(/**something*/) .click() .should(/**something*/) cy.get(/**something else*/) .should(/**something*/) Copy cy.get('#foo') // Once #foo is found the following: .contains('Submit') .click() // ^ will continue to search for something that has text `Submit` and fail if it times out. // ^ After it is found trigger a click on the HTML Node that contained the text `Submit`. Copy // If there is no request against the `foo` alias cypress will wait for 4 seconds automatically cy.wait('@foo') // If there is no element with id #foo cypress will wait for 4 seconds automatically and keep retrying cy.get('#foo') Copy cy.get('#foo') // Once #foo is found the following: .contains('Submit') .click() // ^ Error: #foo does not have anything that `contains` `'Submit'` Copy cy.server() .route('POST', 'https://example.com/api/application/load') .as('load') // create an alias // Start test cy.visit('/') // wait for the call cy.wait('@load') // Now the data is loaded Copy cy.server() .route('POST', 'https://example.com/api/application/load', /* Example payload response */{success:true}); Copy cy.route({ method: 'POST', url: 'https://example.com/api/application/load', onRequest: (xhr) => { // Example assertion expect(xhr.request.body.data).to.deep.equal({success:true}); } }) Copy cy.visit('/'); cy.wait(waitMilliseconds); cy.get('#logoutNotification').should('be.visible'); Copy cy.clock(); cy.visit('/'); cy.tick(waitMilliseconds); cy.get('#logoutNotification').should('be.visible'); Copy import { once } from '../../../src/app/utils'; // Later it('should only call function once', () => { let called = 0; const callMe = once(()=>called++); callMe(); callMe(); expect(called).to.equal(1); }); Copy import { navigate } from 'takeme'; export function foo() { navigate('/foo'); } Copy /// import { foo } from '../../../src/app/foo'; import * as takeme from 'takeme'; describe('should work', () => { it('should stub it', () => { cy.stub(takeme, 'navigate'); foo(); expect(takeme.navigate).to.have.been.calledWith('/foo'); }); }); Copy /// describe('Hello world', () => { it('demonstrate command - execution separation', () => { console.log('start'); cy.visit('http://www.google.com'); console.log('between'); cy.get('.gLFyf').type('Hello world'); console.log('end'); }); }); Copy { "scripts": { "start-server": "npm start", "run-tests": "mocha e2e-spec.js", "ci": "start-server-and-test start-server http://localhost:8080 run-tests" } } --- # Exception Handling | TypeScript Deep Dive JavaScript has an `Error` class that you can use for exceptions. You throw an error with the `throw` keyword. You can catch it with a `try` / `catch` block pair e.g. Copy try { throw new Error('Something bad happened'); } catch(e) { console.log(e); } [](https://basarat.gitbook.io/typescript/type-system/exceptions#error-sub-types) Error Sub Types ----------------------------------------------------------------------------------------------------- Beyond the built in `Error` class there are a few additional built-in error classes that inherit from `Error` that the JavaScript runtime can throw: ### [](https://basarat.gitbook.io/typescript/type-system/exceptions#rangeerror) RangeError Creates an instance representing an error that occurs when a numeric variable or parameter is outside of its valid range. Copy // Call console with too many arguments console.log.apply(console, new Array(1000000000)); // RangeError: Invalid array length ### [](https://basarat.gitbook.io/typescript/type-system/exceptions#referenceerror) ReferenceError Creates an instance representing an error that occurs when de-referencing an invalid reference. e.g. Copy 'use strict'; console.log(notValidVar); // ReferenceError: notValidVar is not defined ### [](https://basarat.gitbook.io/typescript/type-system/exceptions#syntaxerror) SyntaxError Creates an instance representing a syntax error that occurs while parsing code that isn't valid JavaScript. ### [](https://basarat.gitbook.io/typescript/type-system/exceptions#typeerror) TypeError Creates an instance representing an error that occurs when a variable or parameter is not of a valid type. ### [](https://basarat.gitbook.io/typescript/type-system/exceptions#urierror) URIError Creates an instance representing an error that occurs when `encodeURI()` or `decodeURI()` are passed invalid parameters. [](https://basarat.gitbook.io/typescript/type-system/exceptions#always-use-error) Always use `Error` --------------------------------------------------------------------------------------------------------- Beginner JavaScript developers sometimes just throw raw strings e.g. _Don't do that_. The fundamental benefit of `Error` objects is that they automatically keep track of where they were built and originated with the `stack` property. Raw strings result in a very painful debugging experience and complicate error analysis from logs. [](https://basarat.gitbook.io/typescript/type-system/exceptions#you-dont-have-to-throw-an-error) You don't have to `throw` an error ---------------------------------------------------------------------------------------------------------------------------------------- It is okay to pass an `Error` object around. This is conventional in Node.js callback style code which takes callbacks with the first argument as an error object. [](https://basarat.gitbook.io/typescript/type-system/exceptions#exceptional-cases) Exceptional cases --------------------------------------------------------------------------------------------------------- `Exceptions should be exceptional` is a common saying in computer science. There are a few reasons why this is true for JavaScript (and TypeScript) as well. ### [](https://basarat.gitbook.io/typescript/type-system/exceptions#unclear-where-it-is-thrown) Unclear where it is thrown Consider the following piece of code: The next developer cannot know which function might throw the error. The person reviewing the code cannot know without reading the code for task1 / task2 and other functions they might call etc. ### [](https://basarat.gitbook.io/typescript/type-system/exceptions#makes-graceful-handling-hard) Makes graceful handling hard You can try to make it graceful with explicit catch around each thing that might throw: But now if you need to pass stuff from the first task to the second one the code becomes messy: (notice `foo` mutation requiring `let` + explicit need for annotating it because it cannot be inferred from the return of `runTask1`): ### [](https://basarat.gitbook.io/typescript/type-system/exceptions#not-well-represented-in-the-type-system) Not well represented in the type system Consider the function: Using `Error` for such cases is a bad idea as it is not represented in the type definition for the validate function (which is `(value:number) => void`). Instead a better way to create a validate method would be: And now its represented in the type system. > Unless you want to handle the error in a very generic (simple / catch-all etc) way, don't _throw_ an error. [PreviousMoving Types](https://basarat.gitbook.io/typescript/type-system/moving-types) [NextMixins](https://basarat.gitbook.io/typescript/type-system/mixins) Last updated 5 years ago * [Error Sub Types](https://basarat.gitbook.io/typescript/type-system/exceptions#error-sub-types) * [RangeError](https://basarat.gitbook.io/typescript/type-system/exceptions#rangeerror) * [ReferenceError](https://basarat.gitbook.io/typescript/type-system/exceptions#referenceerror) * [SyntaxError](https://basarat.gitbook.io/typescript/type-system/exceptions#syntaxerror) * [TypeError](https://basarat.gitbook.io/typescript/type-system/exceptions#typeerror) * [URIError](https://basarat.gitbook.io/typescript/type-system/exceptions#urierror) * [Always use Error](https://basarat.gitbook.io/typescript/type-system/exceptions#always-use-error) * [You don't have to throw an error](https://basarat.gitbook.io/typescript/type-system/exceptions#you-dont-have-to-throw-an-error) * [Exceptional cases](https://basarat.gitbook.io/typescript/type-system/exceptions#exceptional-cases) * [Unclear where it is thrown](https://basarat.gitbook.io/typescript/type-system/exceptions#unclear-where-it-is-thrown) * [Makes graceful handling hard](https://basarat.gitbook.io/typescript/type-system/exceptions#makes-graceful-handling-hard) * [Not well represented in the type system](https://basarat.gitbook.io/typescript/type-system/exceptions#not-well-represented-in-the-type-system) Copy 1***3; // SyntaxError: Unexpected token * Copy ('1.2').toPrecision(1); // TypeError: '1.2'.toPrecision is not a function Copy decodeURI('%'); // URIError: URI malformed Copy try { throw 'Something bad happened'; } catch(e) { console.log(e); } Copy function myFunction (callback: (e?: Error)) { doSomethingAsync(function () { if (somethingWrong) { callback(new Error('This is my error')) } else { callback(); } }); } Copy try { const foo = runTask1(); const bar = runTask2(); } catch(e) { console.log('Error:', e); } Copy try { const foo = runTask1(); } catch(e) { console.log('Error:', e); } try { const bar = runTask2(); } catch(e) { console.log('Error:', e); } Copy let foo: number; // Notice use of `let` and explicit type annotation try { foo = runTask1(); } catch(e) { console.log('Error:', e); } try { const bar = runTask2(foo); } catch(e) { console.log('Error:', e); } Copy function validate(value: number) { if (value < 0 || value > 100) throw new Error('Invalid value'); } Copy function validate(value: number): {error?: string} { if (value < 0 || value > 100) return {error:'Invalid value'}; } --- # Trivia | TypeScript Deep Dive Trivia (called that because it's `trivial`) represent the parts of the source text that are largely insignificant for normal understanding of the code. For example; whitespace, comments, and even conflict markers. Trivia is _not stored_ in the AST (to keep it lightweight). However, it can be fetched _on demand_ using a few `ts.*` APIs. Before we show them you need to understand the following: [](https://basarat.gitbook.io/typescript/overview/ast/ast-trivia#trivia-ownership) Trivia Ownership -------------------------------------------------------------------------------------------------------- In General: * A token owns any trivia after it on the _same_ line _upto_ the next token. * Any comment _after that line_ is associated with the following token. For leading and ending comments in a file: * The first token in the source file gets all the initial trivia. * The last sequence of trivia in the file is tacked onto the end-of-file token, which otherwise has zero width. [](https://basarat.gitbook.io/typescript/overview/ast/ast-trivia#trivia-apis) Trivia APIs ---------------------------------------------------------------------------------------------- For most basic uses, comments are the "interesting" trivia. The comments that belong to a Node can be fetched through the following functions: Function Description `ts.getLeadingCommentRanges` Given the source text and position within that text, returns ranges of comments between the first line break following the given position and the token itself (probably most useful with `ts.Node.getFullStart`). `ts.getTrailingCommentRanges` Given the source text and position within that text, returns ranges of comments until the first line break following the given position (probably most useful with `ts.Node.getEnd`). As an example, imagine this portion of a source file: Copy debugger;/*hello*/ //bye /*hi*/ function `getLeadingCommentRanges` for the `function` will only return the last 2 comments `//bye` and `/*hi*/`. Appropriately, calling `getTrailingCommentRanges` on the end of the debugger statement will extract the `/*hello*/` comment. [](https://basarat.gitbook.io/typescript/overview/ast/ast-trivia#token-start-full-start) Token Start/Full Start -------------------------------------------------------------------------------------------------------------------- Nodes have what is called a "token start" and a "full start". * Token Start: the more natural version, which is the position in file where the text of a token begins * Full Start: the point at which the scanner began scanning since the last significant token AST nodes have an API for `getStart` and `getFullStart`. In the following example: for `function` the token start is at `function` whereas _full_ start is at `/*hello*/`. Note that full start even includes the trivia that would otherwise be owned by the previous node. [PreviousTIP: SyntaxKind enum](https://basarat.gitbook.io/typescript/overview/ast/ast-tip-syntaxkind) [NextScanner](https://basarat.gitbook.io/typescript/overview/scanner) Last updated 5 years ago * [Trivia Ownership](https://basarat.gitbook.io/typescript/overview/ast/ast-trivia#trivia-ownership) * [Trivia APIs](https://basarat.gitbook.io/typescript/overview/ast/ast-trivia#trivia-apis) * [Token Start/Full Start](https://basarat.gitbook.io/typescript/overview/ast/ast-trivia#token-start-full-start) Copy debugger;/*hello*/ //bye /*hi*/ function --- # StyleGuide | TypeScript Deep Dive > An unofficial TypeScript Style Guide People have asked me for my opinions on this. Personally I don't enforce these a lot on my teams and projects but it does help to have these mentioned as a tiebreaker when someone feels the need to have such strong consistency. There are other things that I feel much more strongly about and those are covered in the [tips chapter](https://basarat.gitbook.io/typescript/main-1) (e.g. type assertion is bad, property setters are bad) ๐ŸŒน. Key Sections: * [Variable](https://basarat.gitbook.io/typescript/styleguide#variable-and-function) * [Class](https://basarat.gitbook.io/typescript/styleguide#class) * [Interface](https://basarat.gitbook.io/typescript/styleguide#interface) * [Type](https://basarat.gitbook.io/typescript/styleguide#type) * [Namespace](https://basarat.gitbook.io/typescript/styleguide#namespace) * [Enum](https://basarat.gitbook.io/typescript/styleguide#enum) * [`null` vs. `undefined`](https://basarat.gitbook.io/typescript/styleguide#null-vs-undefined) * [Formatting](https://basarat.gitbook.io/typescript/styleguide#formatting) * [Single vs. Double Quotes](https://basarat.gitbook.io/typescript/styleguide#quotes) * [Tabs vs. Spaces](https://basarat.gitbook.io/typescript/styleguide#spaces) * [Use semicolons](https://basarat.gitbook.io/typescript/styleguide#semicolons) * [Annotate Arrays as `Type[]`](https://basarat.gitbook.io/typescript/styleguide#array) * [File Names](https://basarat.gitbook.io/typescript/styleguide#filename) * [`type` vs `interface`](https://basarat.gitbook.io/typescript/styleguide#type-vs-interface) * [`==` or `===`](https://basarat.gitbook.io/typescript/styleguide#-or-) [](https://basarat.gitbook.io/typescript/styleguide#variable-and-function) Variable and Function ----------------------------------------------------------------------------------------------------- * Use `camelCase` for variable and function names > Reason: Conventional JavaScript **Bad** **Good** [](https://basarat.gitbook.io/typescript/styleguide#class) Class --------------------------------------------------------------------- * Use `PascalCase` for class names. > Reason: This is actually fairly conventional in standard JavaScript. **Bad** **Good** * Use `camelCase` of class members and methods > Reason: Naturally follows from variable and function naming convention. **Bad** **Good** [](https://basarat.gitbook.io/typescript/styleguide#interface) Interface ----------------------------------------------------------------------------- * Use `PascalCase` for name. > Reason: Similar to class * Use `camelCase` for members. > Reason: Similar to class * **Don't** prefix with `I` > Reason: Unconventional. `lib.d.ts` defines important interfaces without an `I` (e.g. Window, Document etc). **Bad** **Good** [](https://basarat.gitbook.io/typescript/styleguide#type) Type ------------------------------------------------------------------- * Use `PascalCase` for name. > Reason: Similar to class * Use `camelCase` for members. > Reason: Similar to class [](https://basarat.gitbook.io/typescript/styleguide#namespace) Namespace ----------------------------------------------------------------------------- * Use `PascalCase` for names > Reason: Convention followed by the TypeScript team. Namespaces are effectively just a class with static members. Class names are `PascalCase` => Namespace names are `PascalCase` **Bad** **Good** [](https://basarat.gitbook.io/typescript/styleguide#enum) Enum ------------------------------------------------------------------- * Use `PascalCase` for enum names > Reason: Similar to Class. Is a Type. **Bad** **Good** * Use `PascalCase` for enum member > Reason: Convention followed by TypeScript team i.e. the language creators e.g `SyntaxKind.StringLiteral`. Also helps with translation (code generation) of other languages into TypeScript. **Bad** **Good** [](https://basarat.gitbook.io/typescript/styleguide#null-vs.-undefined) Null vs. Undefined ----------------------------------------------------------------------------------------------- * Prefer not to use either for explicit unavailability > Reason: these values are commonly used to keep a consistent structure between values. In TypeScript you use _types_ to denote the structure **Bad** **Good** * Use `undefined` in general (do consider returning an object like `{valid:boolean, value?:Foo}` instead) **Bad** **Good** * Use `null` where it's a part of the API or conventional > Reason: It is conventional in Node.js e.g. `error` is `null` for NodeBack style callbacks. **Bad** **Good** * Use _truthy_ check for **objects** being `null` or `undefined` **Bad** **Good** * Use `== null` / `!= null` (not `===` / `!==`) to check for `null` / `undefined` on primitives as it works for both `null`/`undefined` but not other falsy values (like `''`, `0`, `false`) e.g. **Bad** **Good** [](https://basarat.gitbook.io/typescript/styleguide#formatting) Formatting ------------------------------------------------------------------------------- The TypeScript compiler ships with a very nice formatting language service. Whatever output it gives by default is good enough to reduce the cognitive overload on the team. Use [`tsfmt`](https://github.com/vvakame/typescript-formatter) to automatically format your code on the command line. Also, your IDE (atom/vscode/vs/sublime) already has formatting support built-in. Examples: [](https://basarat.gitbook.io/typescript/styleguide#quotes) Quotes ----------------------------------------------------------------------- * Prefer single quotes (`'`) unless escaping. > Reason: More JavaScript teams do this (e.g. [airbnb](https://github.com/airbnb/javascript) > , [standard](https://github.com/feross/standard) > , [npm](https://github.com/npm/npm) > , [node](https://github.com/nodejs/node) > , [google/angular](https://github.com/angular/angular/) > , [facebook/react](https://github.com/facebook/react) > ). It's easier to type (no shift needed on most keyboards). [Prettier team recommends single quotes as well](https://github.com/prettier/prettier/issues/1105) > Double quotes are not without merit: Allows easier copy paste of objects into JSON. Allows people to use other languages to work without changing their quote character. Allows you to use apostrophes e.g. `He's not going.`. But I'd rather not deviate from where the JS Community is fairly decided. * When you can't use double quotes, try using back ticks (\`). > Reason: These generally represent the intent of complex enough strings. [](https://basarat.gitbook.io/typescript/styleguide#spaces) Spaces ----------------------------------------------------------------------- * Use `2` spaces. Not tabs. > Reason: More JavaScript teams do this (e.g. [airbnb](https://github.com/airbnb/javascript) > , [idiomatic](https://github.com/rwaldron/idiomatic.js) > , [standard](https://github.com/feross/standard) > , [npm](https://github.com/npm/npm) > , [node](https://github.com/nodejs/node) > , [google/angular](https://github.com/angular/angular/) > , [facebook/react](https://github.com/facebook/react) > ). The TypeScript/VSCode teams use 4 spaces but are definitely the exception in the ecosystem. [](https://basarat.gitbook.io/typescript/styleguide#semicolons) Semicolons ------------------------------------------------------------------------------- * Use semicolons. > Reasons: Explicit semicolons helps language formatting tools give consistent results. Missing ASI (automatic semicolon insertion) can trip new devs e.g. `foo() \n (function(){})` will be a single statement (not two). TC39 [warning on this as well](https://github.com/tc39/ecma262/pull/1062) > . Example teams: [airbnb](https://github.com/airbnb/javascript) > , [idiomatic](https://github.com/rwaldron/idiomatic.js) > , [google/angular](https://github.com/angular/angular/) > , [facebook/react](https://github.com/facebook/react) > , [Microsoft/TypeScript](https://github.com/Microsoft/TypeScript/) > . [](https://basarat.gitbook.io/typescript/styleguide#array) Array --------------------------------------------------------------------- * Annotate arrays as `foos: Foo[]` instead of `foos: Array`. > Reasons: It's easier to read. It's used by the TypeScript team. Makes easier to know something is an array as the mind is trained to detect `[]`. [](https://basarat.gitbook.io/typescript/styleguide#filename) Filename --------------------------------------------------------------------------- Name files with `camelCase`. E.g. `utils.ts`, `map.ts` etc. > Reason: Conventional across many JS teams. When the file exports a component and your framework (like React) wants component to be PascalCased, use pascal case file name to match e.g. `Accordion.tsx`, `MyControl.tsx`. > Reason: Helps with consistency (little overthought required) and its what the ecosystem is doing. [](https://basarat.gitbook.io/typescript/styleguide#type-vs.-interface) type vs. interface ----------------------------------------------------------------------------------------------- * Use `type` when you _might_ need a union or intersection: * Use `interface` when you want `extends` or `implements` e.g. * Otherwise use whatever makes you happy that day. I use [type](https://www.youtube.com/watch?v=IXAT3If0pGI) [](https://basarat.gitbook.io/typescript/styleguide#or) `==` or `===` -------------------------------------------------------------------------- Both are [mostly safe for TypeScript users](https://www.youtube.com/watch?v=vBhRXMDlA18) . I use `===` as that is what is used in the TypeScript codebase. [PreviousTypesafe Event Emitter](https://basarat.gitbook.io/typescript/main-1/typed-event) [NextTypeScript Compiler Internals](https://basarat.gitbook.io/typescript/overview) Last updated 3 years ago * [Variable and Function](https://basarat.gitbook.io/typescript/styleguide#variable-and-function) * [Class](https://basarat.gitbook.io/typescript/styleguide#class) * [Interface](https://basarat.gitbook.io/typescript/styleguide#interface) * [Type](https://basarat.gitbook.io/typescript/styleguide#type) * [Namespace](https://basarat.gitbook.io/typescript/styleguide#namespace) * [Enum](https://basarat.gitbook.io/typescript/styleguide#enum) * [Null vs. Undefined](https://basarat.gitbook.io/typescript/styleguide#null-vs.-undefined) * [Formatting](https://basarat.gitbook.io/typescript/styleguide#formatting) * [Quotes](https://basarat.gitbook.io/typescript/styleguide#quotes) * [Spaces](https://basarat.gitbook.io/typescript/styleguide#spaces) * [Semicolons](https://basarat.gitbook.io/typescript/styleguide#semicolons) * [Array](https://basarat.gitbook.io/typescript/styleguide#array) * [Filename](https://basarat.gitbook.io/typescript/styleguide#filename) * [type vs. interface](https://basarat.gitbook.io/typescript/styleguide#type-vs.-interface) * [\== or ===](https://basarat.gitbook.io/typescript/styleguide#or) Copy var FooVar; function BarFunc() { } Copy var fooVar; function barFunc() { } Copy class foo { } Copy class Foo { } Copy class Foo { Bar: number; Baz() { } } Copy class Foo { bar: number; baz() { } } Copy interface IFoo { } Copy interface Foo { } Copy namespace foo { } Copy namespace Foo { } Copy enum color { } Copy enum Color { } Copy enum Color { red } Copy enum Color { Red } Copy let foo = { x: 123, y: undefined }; Copy let foo: { x: number, y?: number } = { x:123 }; Copy return null; Copy return undefined; Copy cb(undefined) Copy cb(null) Copy if (error === null) Copy if (error) Copy if (error !== null) // does not rule out undefined Copy if (error != null) // rules out both null and undefined Copy // Space before type i.e. foo:string const foo: string = "hello"; Copy type Foo = number | { someProperty: number } Copy interface Foo { foo: string; } interface FooBar extends Foo { bar: string; } class X implements FooBar { foo: string; bar: string; } --- # Currying | TypeScript Deep Dive Just use a chain of fat arrow functions: Copy // A curried function let add = (x: number) => (y: number) => x + y; // Simple usage add(123)(456); // partially applied let add123 = add(123); // fully apply the function add123(456); [PreviousStateful Functions](https://basarat.gitbook.io/typescript/main-1/statefulfunctions) [NextType Instantiation](https://basarat.gitbook.io/typescript/main-1/typeinstantiation) Last updated 5 years ago --- # TIPs | TypeScript Deep Dive In this section we present a number of tips that we have collected over the course of using TypeScript in the real world. [PreviousChangelog](https://basarat.gitbook.io/typescript/intro-2/changelog) [NextString Based Enums](https://basarat.gitbook.io/typescript/main-1/stringenums) Last updated 5 years ago --- # Index Signatures | TypeScript Deep Dive An `Object` in JavaScript (and hence TypeScript) can be accessed with a **string** to hold a reference to any other JavaScript **object**. Here is a quick example: Copy let foo: any = {}; foo['Hello'] = 'World'; console.log(foo['Hello']); // World We store a string `"World"` under the key `"Hello"`. Remember we said it can store any JavaScript **object**, so lets store a class instance just to show the concept: Copy class Foo { constructor(public message: string){}; log(){ console.log(this.message) } } let foo: any = {}; foo['Hello'] = new Foo('World'); foo['Hello'].log(); // World Also remember that we said that it can be accessed with a **string**. If you pass any other object to the index signature the JavaScript runtime actually calls `.toString` on it before getting the result. This is demonstrated below: Copy let obj = { toString(){ console.log('toString called') return 'Hello' } } let foo: any = {}; foo[obj] = 'World'; // toString called console.log(foo[obj]); // toString called, World console.log(foo['Hello']); // World Note that `toString` will get called whenever the `obj` is used in an index position. Arrays are slightly different. For `number` indexing JavaScript VMs will try to optimise (depending on things like is it actually an array and do the structures of items stored match etc.). So `number` should be considered as a valid object accessor in its own right (distinct from `string`). Here is a simple array example: So that's JavaScript. Now let's look at TypeScript's graceful handling of this concept. [](https://basarat.gitbook.io/typescript/type-system/index-signatures#typescript-index-signature) TypeScript Index Signature --------------------------------------------------------------------------------------------------------------------------------- First off, because JavaScript _implicitly_ calls `toString` on any object index signature, TypeScript will give you an error to prevent beginners from shooting themselves in the foot (I see users shooting themselves in the foot when using JavaScript all the time on stackoverflow): The reason for forcing the user to be explicit is because the default `toString` implementation on an object is pretty awful, e.g. on v8 it always returns `[object Object]`: Of course `number` is supported because 1. its needed for excellent Array / Tuple support. 2. even if you use it for an `obj` its default `toString` implementation is nice (not `[object Object]`). Point 2 is shown below: So lesson 1: > TypeScript index signatures must be either `string` or `number` Quick note: `symbols` are also valid and supported by TypeScript. But let's not go there just yet. Baby steps. ### [](https://basarat.gitbook.io/typescript/type-system/index-signatures#declaring-an-index-signature) Declaring an index signature So we've been using `any` to tell TypeScript to let us do whatever we want. We can actually specify an _index_ signature explicitly. E.g. say you want to make sure that anything that is stored in an object using a string conforms to the structure `{message: string}`. This can be done with the declaration `{ [index:string] : {message: string} }`. This is demonstrated below: > TIP: the name of the index signature e.g. `index` in `{ [index:string] : {message: string} }` has no significance for TypeScript and is only for readability. e.g. if it's user names you can do `{ [username:string] : {message: string} }` to help the next dev who looks at the code (which just might happen to be you). Of course `number` indexes are also supported e.g. `{ [count: number] : SomeOtherTypeYouWantToStoreEgRebate }` ### [](https://basarat.gitbook.io/typescript/type-system/index-signatures#all-members-must-conform-to-the-string-index-signature) All members must conform to the `string` index signature As soon as you have a `string` index signature, all explicit members must also conform to that index signature. This is shown below: This is to provide safety so that any string access gives the same result: ### [](https://basarat.gitbook.io/typescript/type-system/index-signatures#using-a-limited-set-of-string-literals) Using a limited set of string literals An index signature can require that index strings be members of a union of literal strings by using _Mapped Types_ e.g.: This is often used together with `keyof typeof` to capture vocabulary types, described on the next page. The specification of the vocabulary can be deferred generically: ### [](https://basarat.gitbook.io/typescript/type-system/index-signatures#having-both-string-and-number-indexers) Having both `string` and `number` indexers This is not a common use case, but TypeScript compiler supports it nonetheless. However, it has the restriction that the `string` indexer is more strict than the `number` indexer. This is intentional e.g. to allow typing stuff like: ### [](https://basarat.gitbook.io/typescript/type-system/index-signatures#design-pattern-nested-index-signature) Design Pattern: Nested index signature > API consideration when adding index signatures Quite commonly in the JS community you will see APIs that abuse string indexers. e.g. a common pattern among CSS in JS libraries: Try not to mix string indexers with _valid_ values this way. E.g. a typo in the padding will remain uncaught: Instead separate out the nesting into its own property e.g. in a name like `nest` (or `children` or `subnodes` etc.): ### [](https://basarat.gitbook.io/typescript/type-system/index-signatures#excluding-certain-properties-from-the-index-signature) Excluding certain properties from the index signature Sometimes you need to combine properties into the index signature. This is not advised, and you _should_ use the Nested index signature pattern mentioned above. However, if you are modeling _existing JavaScript_ you can get around it with an intersection type. The following shows an example of the error you will encounter without using an intersection: Here is the workaround using an intersection type: Note that even though you can declare it to model existing JavaScript, you cannot create such an object using TypeScript: [PreviousDiscriminated Unions](https://basarat.gitbook.io/typescript/type-system/discriminated-unions) [NextMoving Types](https://basarat.gitbook.io/typescript/type-system/moving-types) Last updated 5 years ago * [TypeScript Index Signature](https://basarat.gitbook.io/typescript/type-system/index-signatures#typescript-index-signature) * [Declaring an index signature](https://basarat.gitbook.io/typescript/type-system/index-signatures#declaring-an-index-signature) * [All members must conform to the string index signature](https://basarat.gitbook.io/typescript/type-system/index-signatures#all-members-must-conform-to-the-string-index-signature) * [Using a limited set of string literals](https://basarat.gitbook.io/typescript/type-system/index-signatures#using-a-limited-set-of-string-literals) * [Having both string and number indexers](https://basarat.gitbook.io/typescript/type-system/index-signatures#having-both-string-and-number-indexers) * [Design Pattern: Nested index signature](https://basarat.gitbook.io/typescript/type-system/index-signatures#design-pattern-nested-index-signature) * [Excluding certain properties from the index signature](https://basarat.gitbook.io/typescript/type-system/index-signatures#excluding-certain-properties-from-the-index-signature) Copy let foo = ['World']; console.log(foo[0]); // World Copy let obj = { toString(){ return 'Hello' } } let foo: any = {}; // ERROR: the index signature must be string, number ... foo[obj] = 'World'; // FIX: TypeScript forces you to be explicit foo[obj.toString()] = 'World'; Copy let obj = {message:'Hello'} let foo: any = {}; // ERROR: the index signature must be string, number ... foo[obj] = 'World'; // Here is where you actually stored it! console.log(foo["[object Object]"]); // World Copy console.log((1).toString()); // 1 console.log((2).toString()); // 2 Copy let foo:{ [index:string] : {message: string} } = {}; /** * Must store stuff that conforms to the structure */ /** Ok */ foo['a'] = { message: 'some message' }; /** Error: must contain a `message` of type string. You have a typo in `message` */ foo['a'] = { messages: 'some message' }; /** * Stuff that is read is also type checked */ /** Ok */ foo['a'].message; /** Error: messages does not exist. You have a typo in `message` */ foo['a'].messages; Copy /** Okay */ interface Foo { x: number; y: number; } /** Error */ interface Bar { x: number; y: string; // ERROR: Property `y` must be of type number } Copy interface Foo { x: number; } let foo: Foo = {x:1,y:2}; // Directly foo['x']; // number // Indirectly let x = 'x' foo[x]; // number Copy type Index = 'a' | 'b' | 'c' type FromIndex = { [k in Index]?: number } const good: FromIndex = {b:1, c:2} // Error: // Type '{ b: number; c: number; d: number; }' is not assignable to type 'FromIndex'. // Object literal may only specify known properties, and 'd' does not exist in type 'FromIndex'. const bad: FromIndex = {b:1, c:2, d:3}; Copy type FromSomeIndex = { [key in K]: number } Copy interface ArrStr { [key: string]: string | number; // Must accommodate all members [index: number]: string; // Can be a subset of string indexer // Just an example member length: number; } Copy interface NestedCSS { color?: string; [selector: string]: string | NestedCSS | undefined; } const example: NestedCSS = { color: 'red', '.subclass': { color: 'blue' } } Copy const failsSilently: NestedCSS = { colour: 'red', // No error as `colour` is a valid string selector } Copy interface NestedCSS { color?: string; nest?: { [selector: string]: NestedCSS; } } const example: NestedCSS = { color: 'red', nest: { '.subclass': { color: 'blue' } } } const failsSilently: NestedCSS = { colour: 'red', // TS Error: unknown property `colour` } Copy type FieldState = { value: string } type FormState = { isValid: boolean // Error: Does not conform to the index signature } Copy type FieldState = { value: string } type FormState = { isValid: boolean } & { [fieldName: string]: FieldState } Copy type FieldState = { value: string } type FormState = { isValid: boolean } & { [fieldName: string]: FieldState } // Use it for some JavaScript object you are getting from somewhere declare const foo:FormState; const isValidBool = foo.isValid; const somethingFieldState = foo['something']; // Using it to create a TypeScript object will not work const bar: FormState = { // Error `isValid` not assignable to `FieldState isValid: false } --- # Checker | TypeScript Deep Dive Like we mentioned before _checker_ is the thing that makes TypeScript uniquely more powerful than _just another JavaScript transpiler_. The checker is located in `checker.ts` and at this moment it is 23k+ lines of TypeScript (largest part of the compiler). [](https://basarat.gitbook.io/typescript/overview/checker#usage-by-program) Usage by Program ------------------------------------------------------------------------------------------------- The `checker` is initialized by `program`. The following is a sampling of the call stack (we showed the same one when looking at `binder`): Copy program.getTypeChecker -> ts.createTypeChecker (in checker)-> initializeTypeChecker (in checker) -> for each SourceFile `ts.bindSourceFile` (in binder) // followed by for each SourceFile `ts.mergeSymbolTable` (in checker) [](https://basarat.gitbook.io/typescript/overview/checker#association-with-emitter) Association with Emitter ----------------------------------------------------------------------------------------------------------------- True type checking happens once a call is made to `getDiagnostics`. This function is called e.g. once a request is made to `Program.emit`, in which case the checker returns an `EmitResolver` (program calls the checkers `getEmitResolver` function) which is just a set of functions local to `createTypeChecker`. We will mention this again when we look at the emitter. Here is the call stack right down to `checkSourceFile` (a function local to `createTypeChecker`). Copy program.emit -> emitWorker (program local) -> createTypeChecker.getEmitResolver -> // First call the following functions local to createTypeChecker call getDiagnostics -> getDiagnosticsWorker -> checkSourceFile // then return resolver (already initialized in createTypeChecker using a call to local createResolver()) [PreviousBinder Error Reporting](https://basarat.gitbook.io/typescript/overview/binder/binder-diagnostics) [NextChecker Diagnostics](https://basarat.gitbook.io/typescript/overview/checker/checker-global) Last updated 5 years ago * [Usage by Program](https://basarat.gitbook.io/typescript/overview/checker#usage-by-program) * [Association with Emitter](https://basarat.gitbook.io/typescript/overview/checker#association-with-emitter) --- # Stateful Functions | TypeScript Deep Dive A common feature in other programming languages is usage of the `static` keyword to increase the _lifetime_ (not _scope_) of a function variable to live beyond function invocations. Here is a `C` sample that achieves this: Copy void called() { static count = 0; count++; printf("Called : %d", count); } int main () { called(); // Called : 1 called(); // Called : 2 return 0; } Since JavaScript (or TypeScript) doesn't have function statics you can achieve the same thing using various abstractions that wrap over a local variable e.g. using a `class` : Copy const {called} = new class { count = 0; called = () => { this.count++; console.log(`Called : ${this.count}`); } }; called(); // Called : 1 called(); // Called : 2 > C++ developers also try and achieve this using a pattern they call `functor` (a class that overrides the operator `()`). [PreviousNominal Typing](https://basarat.gitbook.io/typescript/main-1/nominaltyping) [NextCurrying](https://basarat.gitbook.io/typescript/main-1/currying) Last updated 5 years ago --- # Changelog | TypeScript Deep Dive > Reading a markdown file with the progress in the project is easier than reading a commit log. Automatic changelog generation from commit messages is a fairly common pattern nowadays. There is a project called [conventional-changelog](https://github.com/conventional-changelog/conventional-changelog) that generates a changelog from commit messages that follow a _convention_. [](https://basarat.gitbook.io/typescript/intro-2/changelog#commit-message-convention) Commit message convention -------------------------------------------------------------------------------------------------------------------- The most common convention is the _angular_ commit messages convention which is [detailed here](https://github.com/angular/angular.js/blob/master/DEVELOPERS.md#-git-commit-guidelines) . [](https://basarat.gitbook.io/typescript/intro-2/changelog#setup) Setup ---------------------------------------------------------------------------- * Install: Copy npm install standard-version -D * Add a `script` target to your `package.json`: Copy { "scripts": { "release": "standard-version" } } * Optionally : To automatically push the new _git commit and tag_ plus publish to npm add a `postrelease` script: Copy { "scripts": { "release": "standard-version", "postrelease": "git push --follow-tags origin master && npm publish" } } [](https://basarat.gitbook.io/typescript/intro-2/changelog#releasing) Releasing ------------------------------------------------------------------------------------ Simply run: Based on the commit messages `major` | `minor` | `patch` is automatically determined. To _explicitly_ specify a version you can specify `--release-as` e.g.: [PreviousESLint](https://basarat.gitbook.io/typescript/intro-2/eslint) [NextTIPs](https://basarat.gitbook.io/typescript/main-1) Last updated 5 years ago * [Commit message convention](https://basarat.gitbook.io/typescript/intro-2/changelog#commit-message-convention) * [Setup](https://basarat.gitbook.io/typescript/intro-2/changelog#setup) * [Releasing](https://basarat.gitbook.io/typescript/intro-2/changelog#releasing) Copy npm run release Copy npm run release -- --release-as minor --- # String Based Enums | TypeScript Deep Dive Sometimes you need a collection of strings collected under a common key. Prior to TypeScript 2.4, TypeScript only supported number-based enums. If using versions prior to 2.4, a work-around is to use [string literal types to create string based enums by combining with union types](https://basarat.gitbook.io/typescript/type-system/literal-types) . [PreviousTIPs](https://basarat.gitbook.io/typescript/main-1) [NextNominal Typing](https://basarat.gitbook.io/typescript/main-1/nominaltyping) Last updated 5 years ago --- # Discriminated Unions | TypeScript Deep Dive [](https://basarat.gitbook.io/typescript/type-system/discriminated-unions#discriminated-union) Discriminated Union ----------------------------------------------------------------------------------------------------------------------- If you have a class with a [_literal member_](https://basarat.gitbook.io/typescript/type-system/literal-types) then you can use that property to discriminate between union members. As an example consider the union of a `Square` and `Rectangle`, here we have a member `kind` that exists on both union members and is of a particular _literal type_: Copy interface Square { kind: "square"; size: number; } interface Rectangle { kind: "rectangle"; width: number; height: number; } type Shape = Square | Rectangle; If you use a type guard style check (`==`, `===`, `!=`, `!==`) or `switch` on the _discriminant property_ (here `kind`) TypeScript will realize that the object must be of the type that has that specific literal and do a type narrowing for you :) Copy function area(s: Shape) { if (s.kind === "square") { // Now TypeScript *knows* that `s` must be a square ;) // So you can use its members safely :) return s.size * s.size; } else { // Wasn't a square? So TypeScript will figure out that it must be a Rectangle ;) // So you can use its members safely :) return s.width * s.height; } } [](https://basarat.gitbook.io/typescript/type-system/discriminated-unions#exhaustive-checks) Exhaustive Checks ------------------------------------------------------------------------------------------------------------------- Quite commonly you want to make sure that all members of a union have some code(action) against them. As an example of where stuff goes bad: You can do that by simply adding a fall through and making sure that the inferred type in that block is compatible with the `never` type. For example if you add the exhaustive check you get a nice error: That forces you to handle this new case : [](https://basarat.gitbook.io/typescript/type-system/discriminated-unions#switch) Switch --------------------------------------------------------------------------------------------- TIP: of course you can also do it in a `switch` statement: [](https://basarat.gitbook.io/typescript/type-system/discriminated-unions#strictnullchecks) strictNullChecks ----------------------------------------------------------------------------------------------------------------- If using _strictNullChecks_ and doing exhaustive checks, TypeScript might complain "not all code paths return a value". You can silence that by simply returning the `_exhaustiveCheck` variable (of type `never`). So: [](https://basarat.gitbook.io/typescript/type-system/discriminated-unions#throw-in-exhaustive-checks) Throw in exhaustive checks ------------------------------------------------------------------------------------------------------------------------------------- You can write a function that takes a `never` (and therefore can only be called with a variable that is inferred as `never`) and then throws an error if its body ever executes: Example use with the area function: [](https://basarat.gitbook.io/typescript/type-system/discriminated-unions#retrospective-versioning) Retrospective Versioning --------------------------------------------------------------------------------------------------------------------------------- Say you have a data structure of the form: And after you have a bunch of `DTO`s you realize that `name` was a poor choice. You can add versioning retrospectively by creating a new _union_ with _literal number_ (or string if you want) of DTO. Mark the version 0 as `undefined` and if you have _strictNullChecks_ enabled it will just work out: Example usage of such a DTO: [](https://basarat.gitbook.io/typescript/type-system/discriminated-unions#redux) Redux ------------------------------------------------------------------------------------------- A popular library that makes use of this is redux. Here is the [_gist of redux_](https://github.com/reactjs/redux#the-gist) with TypeScript type annotations added: Using it with TypeScript gives you safety against typo errors, increased refactor-ability and self documenting code. [PreviousNever Type](https://basarat.gitbook.io/typescript/type-system/never) [NextIndex Signatures](https://basarat.gitbook.io/typescript/type-system/index-signatures) Last updated 5 years ago * [Discriminated Union](https://basarat.gitbook.io/typescript/type-system/discriminated-unions#discriminated-union) * [Exhaustive Checks](https://basarat.gitbook.io/typescript/type-system/discriminated-unions#exhaustive-checks) * [Switch](https://basarat.gitbook.io/typescript/type-system/discriminated-unions#switch) * [strictNullChecks](https://basarat.gitbook.io/typescript/type-system/discriminated-unions#strictnullchecks) * [Throw in exhaustive checks](https://basarat.gitbook.io/typescript/type-system/discriminated-unions#throw-in-exhaustive-checks) * [Retrospective Versioning](https://basarat.gitbook.io/typescript/type-system/discriminated-unions#retrospective-versioning) * [Redux](https://basarat.gitbook.io/typescript/type-system/discriminated-unions#redux) Copy interface Square { kind: "square"; size: number; } interface Rectangle { kind: "rectangle"; width: number; height: number; } // Someone just added this new `Circle` Type // We would like to let TypeScript give an error at any place that *needs* to cater for this interface Circle { kind: "circle"; radius: number; } type Shape = Square | Rectangle | Circle; Copy function area(s: Shape) { if (s.kind === "square") { return s.size * s.size; } else if (s.kind === "rectangle") { return s.width * s.height; } // Would it be great if you could get TypeScript to give you an error? } Copy function area(s: Shape) { if (s.kind === "square") { return s.size * s.size; } else if (s.kind === "rectangle") { return s.width * s.height; } else { // ERROR : `Circle` is not assignable to `never` const _exhaustiveCheck: never = s; } } Copy function area(s: Shape) { if (s.kind === "square") { return s.size * s.size; } else if (s.kind === "rectangle") { return s.width * s.height; } else if (s.kind === "circle") { return Math.PI * (s.radius **2); } else { // Okay once more const _exhaustiveCheck: never = s; } } Copy function area(s: Shape) { switch (s.kind) { case "square": return s.size * s.size; case "rectangle": return s.width * s.height; case "circle": return Math.PI * s.radius * s.radius; default: const _exhaustiveCheck: never = s; } } Copy function area(s: Shape) { switch (s.kind) { case "square": return s.size * s.size; case "rectangle": return s.width * s.height; case "circle": return Math.PI * s.radius * s.radius; default: const _exhaustiveCheck: never = s; return _exhaustiveCheck; } } Copy function assertNever(x:never): never { throw new Error('Unexpected value. Should have been never.'); } Copy interface Square { kind: "square"; size: number; } interface Rectangle { kind: "rectangle"; width: number; height: number; } type Shape = Square | Rectangle; function area(s: Shape) { switch (s.kind) { case "square": return s.size * s.size; case "rectangle": return s.width * s.height; // If a new case is added at compile time you will get a compile error // If a new value appears at runtime you will get a runtime error default: return assertNever(s); } } Copy type DTO = { name: string } Copy type DTO = | { version: undefined, // version 0 name: string, } | { version: 1, firstName: string, lastName: string, } // Even later | { version: 2, firstName: string, middleName: string, lastName: string, } // So on Copy function printDTO(dto:DTO) { if (dto.version == null) { console.log(dto.name); } else if (dto.version == 1) { console.log(dto.firstName,dto.lastName); } else if (dto.version == 2) { console.log(dto.firstName, dto.middleName, dto.lastName); } else { const _exhaustiveCheck: never = dto; } } Copy import { createStore } from 'redux' type Action = { type: 'INCREMENT' } | { type: 'DECREMENT' } /** * This is a reducer, a pure function with (state, action) => state signature. * It describes how an action transforms the state into the next state. * * The shape of the state is up to you: it can be a primitive, an array, an object, * or even an Immutable.js data structure. The only important part is that you should * not mutate the state object, but return a new object if the state changes. * * In this example, we use a `switch` statement and strings, but you can use a helper that * follows a different convention (such as function maps) if it makes sense for your * project. */ function counter(state = 0, action: Action) { switch (action.type) { case 'INCREMENT': return state + 1 case 'DECREMENT': return state - 1 default: return state } } // Create a Redux store holding the state of your app. // Its API is { subscribe, dispatch, getState }. let store = createStore(counter) // You can use subscribe() to update the UI in response to state changes. // Normally you'd use a view binding library (e.g. React Redux) rather than subscribe() directly. // However, it can also be handy to persist the current state in the localStorage. store.subscribe(() => console.log(store.getState()) ) // The only way to mutate the internal state is to dispatch an action. // The actions can be serialized, logged or stored and later replayed. store.dispatch({ type: 'INCREMENT' }) // 1 store.dispatch({ type: 'INCREMENT' }) // 2 store.dispatch({ type: 'DECREMENT' }) // 1 --- # File Module Details | TypeScript Deep Dive There is a lot of power and usability packed into the TypeScript external module pattern. Here we discuss its power and some patterns needed to reflect real world usages. [](https://basarat.gitbook.io/typescript/project/modules/external-modules#clarification-commonjs-amd-es-modules-others) Clarification: commonjs, amd, es modules, others ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- First up we need to clarify the (awful) inconsistency of the module systems out there. I'll just give you my _current_ recommendation and remove the noise i.e. not show you all the _other_ ways things can work. From the _same TypeScript_ you can generate different _JavaScript_ depending upon the `module` option. Here are things you can ignore (I am not interested in explaining dead tech): * AMD: Do not use. Was browser only. * SystemJS: Was a good experiment. Superseded by ES modules. * ES Modules: Not ready yet. Now these are just the options for _generating the JavaScript_. Instead of these options use `module:commonjs` How you _write_ TypeScript modules is also a bit of a mess. Again here is how not to do it _today_: * `import foo = require('foo')`. i.e. `import/require`. Use ES module syntax instead. Cool, with that out of the way, lets look at the ES module syntax. > Summary: Use `module:commonjs` and use the ES module syntax to import / export / author modules. [](https://basarat.gitbook.io/typescript/project/modules/external-modules#es-module-syntax) ES Module syntax ----------------------------------------------------------------------------------------------------------------- * Exporting a variable (or type) is as easy as prefixing the keyword `export` e.g. Copy // file `foo.ts` export let someVar = 123; export type SomeType = { foo: string; }; * Exporting a variable or type in a dedicated `export` statement e.g. * Exporting a variable or type in a dedicated `export` statement _with renaming_ e.g. * Import a variable or a type using `import` e.g. * Import a variable or a type using `import` _with renaming_ e.g. * Import everything from a module into a name with `import * as` e.g. * Import a file _only_ for its side effect with a single import statement: * Re-Exporting all the items from another module * Re-Exporting only some items from another module * Re-Exporting only some items from another module _with renaming_ [](https://basarat.gitbook.io/typescript/project/modules/external-modules#default-exports-imports) Default exports/imports ------------------------------------------------------------------------------------------------------------------------------- As you will learn later, I am not a fan of default exports. Nevertheless here is syntax for export and using default exports * Export using `export default` * before a variable (no `let / const / var` needed) * before a function * before a class * Import using the `import someName from "someModule"` syntax (you can name the import whatever you want) e.g. [](https://basarat.gitbook.io/typescript/project/modules/external-modules#module-paths) Module paths --------------------------------------------------------------------------------------------------------- > I am just going to assume `moduleResolution: "Node"`. This is the option you should have in your TypeScript config. This setting is implied automatically by `module:commonjs`. There are two distinct kinds of modules. The distinction is driven by the path section of the import statement (e.g. `import foo from 'THIS IS THE PATH SECTION'`). * Relative path modules (where path starts with `.` e.g. `./someFile` or `../../someFolder/someFile` etc.) * Other dynamic lookup modules (e.g. `'core-js'` or `'typestyle'` or `'react'` or even `'react/core'` etc.) The main difference is _how the module is resolved on the file system_. > I will use a conceptual term _place_ that I will explain after mentioning the lookup pattern. ### [](https://basarat.gitbook.io/typescript/project/modules/external-modules#relative-path-modules) Relative path modules Easy, just follow the relative path :) e.g. * if file `bar.ts` does `import * as foo from './foo';` then place `foo` must exist in the same folder. * if file `bar.ts` does `import * as foo from '../foo';` then place `foo` must exist in a folder up. * if file `bar.ts` does `import * as foo from '../someFolder/foo';` then one folder up, there must be a folder `someFolder` with a place `foo` Or any other relative path you can think of :) ### [](https://basarat.gitbook.io/typescript/project/modules/external-modules#dynamic-lookup) Dynamic lookup When the import path is _not_ relative, lookup is driven by [_node style resolution_](https://nodejs.org/api/modules.html#modules_all_together) . Here I only give a simple example: * You have `import * as foo from 'foo'`, the following are the places that are checked _in order_ * `./node_modules/foo` * `../node_modules/foo` * `../../node_modules/foo` * Till root of file system * You have `import * as foo from 'something/foo'`, the following are the places that are checked _in order_ * `./node_modules/something/foo` * `../node_modules/something/foo` * `../../node_modules/something/foo` * Till root of file system [](https://basarat.gitbook.io/typescript/project/modules/external-modules#what-is-place) What is _place_ ------------------------------------------------------------------------------------------------------------- When I say _places that are checked_ I mean that the following things are checked in that place. e.g. for a place `foo`: * If the place is a file, e.g. `foo.ts`, hurray! * else if the place is a folder and there is a file `foo/index.ts`, hurray! * else if the place is a folder and there is a `foo/package.json` and a file specified in the `types` key in the package.json that exists, then hurray! * else if the place is a folder and there is a `package.json` and a file specified in the `main` key in the package.json that exists, then hurray! By file I actually mean `.ts` / `.d.ts` and `.js`. And that's it. You are now module lookup experts (not a small feat!). [](https://basarat.gitbook.io/typescript/project/modules/external-modules#overturning-dynamic-lookup-just-for-types) Overturning dynamic lookup _just for types_ --------------------------------------------------------------------------------------------------------------------------------------------------------------------- You can declare a module _globally_ for your project by using `declare module 'somePath'` and then imports will resolve _magically_ to that path e.g. and then: [](https://basarat.gitbook.io/typescript/project/modules/external-modules#import-require-for-importing-type-only) `import/require` for importing type only --------------------------------------------------------------------------------------------------------------------------------------------------------------- The following statement: actually does _two_ things: * Imports the type information of the foo module. * Specifies a runtime dependency on the foo module. You can pick and choose so that only _the type information_ is loaded and no runtime dependency occurs. Before continuing you might want to recap the [_declaration spaces_](https://basarat.gitbook.io/typescript/project/declarationspaces) section of the book. If you do not use the imported name in the variable declaration space then the import is completely removed from the generated JavaScript. This is best explained with examples. Once you understand this we will present you with use cases. ### [](https://basarat.gitbook.io/typescript/project/modules/external-modules#example-1) Example 1 will generate the JavaScript: That's right. An _empty_ file as foo is not used. ### [](https://basarat.gitbook.io/typescript/project/modules/external-modules#example-2) Example 2 will generate the JavaScript: This is because `foo` (or any of its properties e.g. `foo.bas`) is never used as a variable. ### [](https://basarat.gitbook.io/typescript/project/modules/external-modules#example-3) Example 3 will generate the JavaScript (assuming commonjs): This is because `foo` is used as a variable. [](https://basarat.gitbook.io/typescript/project/modules/external-modules#use-case-lazy-loading) Use case: Lazy loading ---------------------------------------------------------------------------------------------------------------------------- Type inference needs to be done _upfront_. This means that if you want to use some type from a file `foo` in a file `bar` you will have to do: However, you might want to only load the file `foo` at runtime under certain conditions. For such cases you should use the `import`ed name only in _type annotations_ and **not** as a _variable_. This removes any _upfront_ runtime dependency code being injected by TypeScript. Then _manually import_ the actual module using code that is specific to your module loader. As an example, consider the following `commonjs` based code where we only load a module `'foo'` on a certain function call: A similar sample in `amd` (using requirejs) would be: This pattern is commonly used: * in web apps where you load certain JavaScript on particular routes, * in node applications where you only load certain modules if needed to speed up application bootup. [](https://basarat.gitbook.io/typescript/project/modules/external-modules#use-case-breaking-circular-dependencies) Use case: Breaking Circular dependencies ---------------------------------------------------------------------------------------------------------------------------------------------------------------- Similar to the lazy loading use case certain module loaders (commonjs/node and amd/requirejs) don't work well with circular dependencies. In such cases it is useful to have _lazy loading_ code in one direction and loading the modules upfront in the other direction. [](https://basarat.gitbook.io/typescript/project/modules/external-modules#use-case-ensure-import) Use case: Ensure Import ------------------------------------------------------------------------------------------------------------------------------ Sometimes you want to load a file just for the side effect (e.g. the module might register itself with some library like [CodeMirror addons](https://codemirror.net/doc/manual.html#addons) etc.). However, if you just do a `import/require` the transpiled JavaScript will not contain a dependency on the module and your module loader (e.g. webpack) might completely ignore the import. In such cases you can use a `ensureImport` variable to ensure that the compiled JavaScript takes a dependency on the module e.g.: [PreviousModules](https://basarat.gitbook.io/typescript/project/modules) [Nextglobal.d.ts](https://basarat.gitbook.io/typescript/project/modules/globals) Last updated 5 years ago * [Clarification: commonjs, amd, es modules, others](https://basarat.gitbook.io/typescript/project/modules/external-modules#clarification-commonjs-amd-es-modules-others) * [ES Module syntax](https://basarat.gitbook.io/typescript/project/modules/external-modules#es-module-syntax) * [Default exports/imports](https://basarat.gitbook.io/typescript/project/modules/external-modules#default-exports-imports) * [Module paths](https://basarat.gitbook.io/typescript/project/modules/external-modules#module-paths) * [Relative path modules](https://basarat.gitbook.io/typescript/project/modules/external-modules#relative-path-modules) * [Dynamic lookup](https://basarat.gitbook.io/typescript/project/modules/external-modules#dynamic-lookup) * [What is place](https://basarat.gitbook.io/typescript/project/modules/external-modules#what-is-place) * [Overturning dynamic lookup just for types](https://basarat.gitbook.io/typescript/project/modules/external-modules#overturning-dynamic-lookup-just-for-types) * [import/require for importing type only](https://basarat.gitbook.io/typescript/project/modules/external-modules#import-require-for-importing-type-only) * [Example 1](https://basarat.gitbook.io/typescript/project/modules/external-modules#example-1) * [Example 2](https://basarat.gitbook.io/typescript/project/modules/external-modules#example-2) * [Example 3](https://basarat.gitbook.io/typescript/project/modules/external-modules#example-3) * [Use case: Lazy loading](https://basarat.gitbook.io/typescript/project/modules/external-modules#use-case-lazy-loading) * [Use case: Breaking Circular dependencies](https://basarat.gitbook.io/typescript/project/modules/external-modules#use-case-breaking-circular-dependencies) * [Use case: Ensure Import](https://basarat.gitbook.io/typescript/project/modules/external-modules#use-case-ensure-import) Copy // file `foo.ts` let someVar = 123; type SomeType = { foo: string; }; export { someVar, SomeType }; Copy // file `foo.ts` let someVar = 123; export { someVar as aDifferentName }; Copy // file `bar.ts` import { someVar, SomeType } from './foo'; Copy // file `bar.ts` import { someVar as aDifferentName } from './foo'; Copy // file `bar.ts` import * as foo from './foo'; // you can use `foo.someVar` and `foo.SomeType` and anything else that foo might export. Copy import 'core-js'; // a common polyfill library Copy export * from './foo'; Copy export { someVar } from './foo'; Copy export { someVar as aDifferentName } from './foo'; Copy // some var export default someVar = 123; // OR Some function export default function someFunction() { } // OR Some class export default class SomeClass { } Copy import someLocalNameForThisFile from "../foo"; Copy // global.d.ts declare module 'foo' { // Some variable declarations export var bar: number; /*sample*/ } Copy // anyOtherTsFileInYourProject.ts import * as foo from 'foo'; // TypeScript assumes (without doing any lookup) that // foo is {bar:number} Copy import foo = require('foo'); Copy import foo = require('foo'); Copy Copy import foo = require('foo'); var bar: foo; Copy var bar; Copy import foo = require('foo'); var bar = foo; Copy var foo = require('foo'); var bar = foo; Copy import foo = require('foo'); var bar: foo.SomeType; Copy import foo = require('foo'); export function loadFoo() { // This is lazy loading `foo` and using the original module *only* as a type annotation var _foo: typeof foo = require('foo'); // Now use `_foo` as a variable instead of `foo`. } Copy import foo = require('foo'); export function loadFoo() { // This is lazy loading `foo` and using the original module *only* as a type annotation require(['foo'], (_foo: typeof foo) => { // Now use `_foo` as a variable instead of `foo`. }); } Copy import foo = require('./foo'); import bar = require('./bar'); import bas = require('./bas'); const ensureImport: any = foo && bar && bas; --- # ESLint | TypeScript Deep Dive ESLint existed to lint JavaScript, but now it is also becoming the defacto linter for [TypeScript](https://github.com/Microsoft/TypeScript/issues/29288) , thanks to the [collaboration](https://eslint.org/blog/2019/01/future-typescript-eslint) between the two teams. [](https://basarat.gitbook.io/typescript/intro-2/eslint#install) Install ----------------------------------------------------------------------------- To setup ESLint for TypeScript you need the following packages: Copy npm i eslint eslint-plugin-react @typescript-eslint/parser @typescript-eslint/eslint-plugin > TIP: eslint calls packages that contain lint rules as "plugin" * eslint : Core eslint * eslint-plugin-react : For react rules provided by eslint. [Supported rules list](https://github.com/yannickcr/eslint-plugin-react#list-of-supported-rules) * @typescript-eslint/parse : To allow eslint to understand ts / tsx files * @typescript-eslint/eslint-plugin : For TypeScript rules. [Supported rules list](https://github.com/typescript-eslint/typescript-eslint/tree/master/packages/eslint-plugin#supported-rules) > As you can see there are two eslint packages (for use with js or ts) and two @typescript-eslint packages (for use with ts). So the overhead for TypeScript is not _that much_. [](https://basarat.gitbook.io/typescript/intro-2/eslint#configure) Configure --------------------------------------------------------------------------------- Create `.eslintrc.js`: Copy module.exports = { parser: '@typescript-eslint/parser', parserOptions: { project: './tsconfig.json', }, plugins: ['@typescript-eslint'], extends: [\ 'plugin:react/recommended',\ 'plugin:@typescript-eslint/recommended',\ ], rules: { // Overwrite rules specified from the extended configs e.g. // "@typescript-eslint/explicit-function-return-type": "off", } } [](https://basarat.gitbook.io/typescript/intro-2/eslint#run) Run --------------------------------------------------------------------- In your `package.json` add to `scripts`: Now you can `npm run lint` to validate. [](https://basarat.gitbook.io/typescript/intro-2/eslint#configure-vscode) Configure VSCode ----------------------------------------------------------------------------------------------- * Install extension [https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint) * Add to `settings.json`: [PreviousHusky](https://basarat.gitbook.io/typescript/intro-2/husky) [NextChangelog](https://basarat.gitbook.io/typescript/intro-2/changelog) Last updated 5 years ago * [Install](https://basarat.gitbook.io/typescript/intro-2/eslint#install) * [Configure](https://basarat.gitbook.io/typescript/intro-2/eslint#configure) * [Run](https://basarat.gitbook.io/typescript/intro-2/eslint#run) * [Configure VSCode](https://basarat.gitbook.io/typescript/intro-2/eslint#configure-vscode) Copy { "scripts": { "lint": "eslint \"src/**\"" } } Copy "eslint.validate": [\ "javascript",\ "javascriptreact",\ {"language": "typescript", "autoFix": true },\ {"language": "typescriptreact", "autoFix": true }\ ], --- # lib.d.ts | TypeScript Deep Dive * [lib.d.ts](https://basarat.gitbook.io/typescript/type-system/lib.d.ts#libdts) * [Example Usage](https://basarat.gitbook.io/typescript/type-system/lib.d.ts#example-usage) * [Inside look](https://basarat.gitbook.io/typescript/type-system/lib.d.ts#libdts-inside-look) * [Modifying Native types](https://basarat.gitbook.io/typescript/type-system/lib.d.ts#modifying-native-types) * [Using custom lib.d.ts](https://basarat.gitbook.io/typescript/type-system/lib.d.ts#using-your-own-custom-libdts) * [Compiler `target` effect on lib.d.ts](https://basarat.gitbook.io/typescript/type-system/lib.d.ts#compiler-target-effect-on-libdts) * [`lib` option](https://basarat.gitbook.io/typescript/type-system/lib.d.ts#lib-option) * [Polyfill for old JavaScript engines](https://basarat.gitbook.io/typescript/type-system/lib.d.ts#polyfill-for-old-javascript-engines) [](https://basarat.gitbook.io/typescript/type-system/lib.d.ts#lib.d.ts) `lib.d.ts` --------------------------------------------------------------------------------------- A special declaration file `lib.d.ts` ships with every installation of TypeScript. This file contains the ambient declarations for various common JavaScript constructs present in JavaScript runtimes and the DOM. * This file is automatically included in the compilation context of a TypeScript project. * The objective of this file is to make it easy for you to start writing _type checked_ JavaScript code. You can exclude this file from the compilation context by specifying the `--noLib` compiler command line flag (or `"noLib" : true` in `tsconfig.json`). ### [](https://basarat.gitbook.io/typescript/type-system/lib.d.ts#example-usage) Example Usage As always let's look at examples of this file being used in action: Copy var foo = 123; var bar = foo.toString(); This code type checks fine _because_ the `toString` function is defined in `lib.d.ts` for all JavaScript objects. If you use the same sample code with the `noLib` option you get a type check error: So now that you understand the importance of `lib.d.ts`, what do its contents look like? We examine that next. ### [](https://basarat.gitbook.io/typescript/type-system/lib.d.ts#lib.d.ts-inside-look) `lib.d.ts` Inside Look The contents of `lib.d.ts` are primarily a bunch of _variable_ declarations e.g. `window`, `document`, `math` and a bunch of similar _interface_ declarations e.g. `Window` , `Document`, `Math`. The simplest way to read the documentation and type annotations of global stuff is to type in code _that you know works_ e.g. `Math.floor` and then F12 (go to definition) using your IDE (VSCode has great support for this). Let's look at a sample _variable_ declaration, e.g. `window` is defined as: That is just a simple `declare var` followed by the variable name (here `window`) and an interface for a type annotation (here the `Window` interface). These variables generally point to some global _interface_ e.g. here is a small sample of the (actually quite massive) `Window` interface: You can see that there is a _lot_ of type information in these interfaces. In the absence of TypeScript _you_ would need to keep this in _your_ head. Now you can offload that knowledge on the compiler with easy access to it using things like `intellisense`. There is a good reason for using _interfaces_ for these globals. It allows you to _add additional properties_ to these globals _without_ a need to change `lib.d.ts`. We will cover this concept next. ### [](https://basarat.gitbook.io/typescript/type-system/lib.d.ts#modifying-native-types) Modifying Native Types Since an `interface` in TypeScript is open ended this means that you can just add members to the interfaces declared in `lib.d.ts` and TypeScript will pick up on the additions. Note that you need to make these changes in a [_global module_](https://basarat.gitbook.io/typescript/project/modules) for these interfaces to be associated with `lib.d.ts`. We even recommend creating a special file called [`global.d.ts`](https://basarat.gitbook.io/typescript/project/modules/globals) for this purpose. Here are a few example cases where we add stuff to `window`, `Math`, `Date`: #### [](https://basarat.gitbook.io/typescript/type-system/lib.d.ts#example-window) Example `window` Just add stuff to the `Window` interface e.g.: This will allow you to use it in a _type safe_ manner: #### [](https://basarat.gitbook.io/typescript/type-system/lib.d.ts#example-math) Example `Math` The global variable `Math` is defined in `lib.d.ts` as (again, use your dev tools to navigate to definition): i.e. the variable `Math` is an instance of the `Math` interface. The `Math` interface is defined as: This means that if you want to add stuff to the `Math` global variable you just need to add it to the `Math` global interface, e.g. consider the [`seedrandom` project](https://www.npmjs.com/package/seedrandom) which adds a `seedrandom` function to the global `Math` object. This can be declared quite easily: And then you can just use it: #### [](https://basarat.gitbook.io/typescript/type-system/lib.d.ts#example-date) Example `Date` If you look at the definition of the `Date` _variable_ in `lib.d.ts` you will find: The interface `DateConstructor` is similar to what you have seen before with `Math` and `Window` in that it contains members you can use off of the `Date` global variable e.g. `Date.now()`. In addition to these members it contains _construct_ signatures which allow you to create `Date` instances (e.g. `new Date()`). A snippet of the `DateConstructor` interface is shown below: Consider the project [`datejs`](https://github.com/abritinthebay/datejs) . DateJS adds members to both the `Date` global variable and `Date` instances. Therefore a TypeScript definition for this library would look like ([BTW the community has already written this for you in this case](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/datejs/index.d.ts) ): This allows you to do stuff like the following in a TypeSafe manner: #### [](https://basarat.gitbook.io/typescript/type-system/lib.d.ts#example-string) Example `string` If you look inside `lib.d.ts` for string you will find stuff similar to what we saw for `Date` (`String` global variable, `StringConstructor` interface, `String` interface). One thing of note though is that the `String` interface also impacts string _literals_ as demonstrated in the below code sample: Similar variables and interfaces exist for other things that have both static and instance members like `Number`, `Boolean`, `RegExp`, etc. and these interfaces affect literal instances of these types as well. ### [](https://basarat.gitbook.io/typescript/type-system/lib.d.ts#example-string-redux) Example `string` redux We recommended creating a `global.d.ts` for maintainability reasons. However, you can break into the _global namespace_ from within _a file module_ if you desire so. This is done using `declare global { /*global namespace here*/ }`. E.g. the previous example can also be done as: ### [](https://basarat.gitbook.io/typescript/type-system/lib.d.ts#using-your-own-custom-lib.d.ts) Using your own custom lib.d.ts As we mentioned earlier, using the `--noLib` boolean compiler flag causes TypeScript to exclude the automatic inclusion of `lib.d.ts`. There are various reasons why this is a useful feature. Here are a few of the common ones: * You are running in a custom JavaScript environment that differs _significantly_ from the standard browser based runtime environment. * You like to have _strict_ control over the _globals_ available in your code. E.g. lib.d.ts defines `item` as a global variable and you don't want this to leak into your code. Once you have excluded the default `lib.d.ts` you can include a similarly named file into your compilation context and TypeScript will pick it up for type checking. > Note: be careful with `--noLib`. Once you are in noLib land, if you choose to share your project with others, they will be _forced_ into noLib land (or rather _your lib_ land). Even worse, if you bring _their_ code into your project you might need to port it to _your lib_ based code. ### [](https://basarat.gitbook.io/typescript/type-system/lib.d.ts#compiler-target-effect-on-lib.d.ts) Compiler target effect on `lib.d.ts` Setting the compiler target to `es6` causes the `lib.d.ts` to include _additional_ ambient declarations for more modern (es6) stuff like `Promise`. This magical effect of the compiler target changing the _ambience_ of the code is desirable for some people and for others it's problematic as it conflates _code generation_ with _code ambience_. However, if you want finer grained control of your environment, you should use the `--lib` option which we discuss next. ### [](https://basarat.gitbook.io/typescript/type-system/lib.d.ts#lib-option) lib option Sometimes (many times) you want to decouple the relationship between the compile target (the generated JavaScript version) and the ambient library support. A common example is `Promise`, e.g. today (in June 2016) you most likely want to `--target es5` but still use the latest features like `Promise`. To support this you can take explicit control of `lib` using the `lib` compiler option. > Note: using `--lib` decouples any lib magic from `--target` giving you better control. You can provide this option on the command line or in `tsconfig.json` (recommended): **Command line**: **tsconfig.json**: The libs can be categorized as follows: * JavaScript Bulk Feature: * es5 * es6 * es2015 * es7 * es2016 * es2017 * esnext * Runtime Environment * dom * dom.iterable * webworker * scripthost * ESNext By-Feature Options (even smaller than bulk feature) * es2015.core * es2015.collection * es2015.generator * es2015.iterable * es2015.promise * es2015.proxy * es2015.reflect * es2015.symbol * es2015.symbol.wellknown * es2016.array.include * es2017.object * es2017.sharedmemory * esnext.asynciterable > NOTE: the `--lib` option provides extremely fine tuned control. So you most likely want to pick an item from the bulk + environment categories. If --lib is not specified a default library is injected: > > * For --target es5 => es5, dom, scripthost > > * For --target es6 => es6, dom, dom.iterable, scripthost > My Personal Recommendation: Example Including Symbol with ES5: Symbol API is not included when target is es5. In fact, we receive an error like: \[ts\] Cannot find name 'Symbol'. We can use "target": "es5" in combination with "lib" to provide Symbol API in TypeScript: [](https://basarat.gitbook.io/typescript/type-system/lib.d.ts#polyfill-for-old-javascript-engines) Polyfill for old JavaScript engines ------------------------------------------------------------------------------------------------------------------------------------------- > [Egghead PRO Video on this subject](https://egghead.io/lessons/typescript-using-es6-and-esnext-with-typescript) There are quite a few runtime features that are like `Map` / `Set` and even `Promise` (this list will of course change over time) that you can use with modern `lib` options. To use these all you need to do is use `core-js`. Simply install: And add an import to your application entry point: And it should polyfill these runtime features for you ๐ŸŒน. [PreviousEnums](https://basarat.gitbook.io/typescript/type-system/enums) [NextFunctions](https://basarat.gitbook.io/typescript/type-system/functions) Last updated 5 years ago * [lib.d.ts](https://basarat.gitbook.io/typescript/type-system/lib.d.ts#lib.d.ts) * [Example Usage](https://basarat.gitbook.io/typescript/type-system/lib.d.ts#example-usage) * [lib.d.ts Inside Look](https://basarat.gitbook.io/typescript/type-system/lib.d.ts#lib.d.ts-inside-look) * [Modifying Native Types](https://basarat.gitbook.io/typescript/type-system/lib.d.ts#modifying-native-types) * [Example string redux](https://basarat.gitbook.io/typescript/type-system/lib.d.ts#example-string-redux) * [Using your own custom lib.d.ts](https://basarat.gitbook.io/typescript/type-system/lib.d.ts#using-your-own-custom-lib.d.ts) * [Compiler target effect on lib.d.ts](https://basarat.gitbook.io/typescript/type-system/lib.d.ts#compiler-target-effect-on-lib.d.ts) * [lib option](https://basarat.gitbook.io/typescript/type-system/lib.d.ts#lib-option) * [Polyfill for old JavaScript engines](https://basarat.gitbook.io/typescript/type-system/lib.d.ts#polyfill-for-old-javascript-engines) Copy var foo = 123; var bar = foo.toString(); // ERROR: Property 'toString' does not exist on type 'number'. Copy declare var window: Window; Copy interface Window extends EventTarget, WindowTimers, WindowSessionStorage, WindowLocalStorage, WindowConsole, GlobalEventHandlers, IDBEnvironment, WindowBase64 { animationStartTime: number; applicationCache: ApplicationCache; clientInformation: Navigator; closed: boolean; crypto: Crypto; // so on and so forth... } Copy interface Window { helloWorld(): void; } Copy // Add it at runtime window.helloWorld = () => console.log('hello world'); // Call it window.helloWorld(); // Misuse it and you get an error: window.helloWorld('gracius'); // Error: Supplied parameters do not match the signature of the call target Copy /** An intrinsic object that provides basic mathematics functionality and constants. */ declare var Math: Math; Copy interface Math { E: number; LN10: number; // others ... } Copy interface Math { seedrandom(seed?: string); } Copy Math.seedrandom(); // or Math.seedrandom("Any string you want!"); Copy declare var Date: DateConstructor; Copy interface DateConstructor { new (): Date; // ... other construct signatures now(): number; // ... other member functions } Copy /** DateJS Public Static Methods */ interface DateConstructor { /** Gets a date that is set to the current date. The time is set to the start of the day (00:00 or 12:00 AM) */ today(): Date; // ... so on and so forth } /** DateJS Public Instance Methods */ interface Date { /** Adds the specified number of milliseconds to this instance. */ addMilliseconds(milliseconds: number): Date; // ... so on and so forth } Copy var today = Date.today(); var todayAfter1second = today.addMilliseconds(1000); Copy interface String { endsWith(suffix: string): boolean; } String.prototype.endsWith = function(suffix: string): boolean { var str: string = this; return str && str.indexOf(suffix, str.length - suffix.length) !== -1; } console.log('foo bar'.endsWith('bas')); // false console.log('foo bas'.endsWith('bas')); // true Copy // Ensure this is treated as a module. export {}; declare global { interface String { endsWith(suffix: string): boolean; } } String.prototype.endsWith = function(suffix: string): boolean { var str: string = this; return str && str.indexOf(suffix, str.length - suffix.length) !== -1; } console.log('foo bar'.endsWith('bas')); // false console.log('foo bas'.endsWith('bas')); // true Copy tsc --target es5 --lib dom,es6 Copy "compilerOptions": { "lib": ["dom", "es6"] } Copy "compilerOptions": { "target": "es5", "lib": ["es6", "dom"] } Copy "compilerOptions": { "target": "es5", "lib": ["es5", "dom", "scripthost", "es2015.symbol"] } Copy npm install core-js --save-dev Copy import "core-js"; --- # singleton pattern | TypeScript Deep Dive The conventional singleton pattern is really something that is used to overcome the fact that all code must be in a `class`. Copy class Singleton { private static instance: Singleton; private constructor() { // do something construct... } static getInstance() { if (!Singleton.instance) { Singleton.instance = new Singleton(); // ... any one time initialization goes here ... } return Singleton.instance; } someMethod() { } } let something = new Singleton() // Error: constructor of 'Singleton' is private. let instance = Singleton.getInstance() // do something with the instance... However, if you don't want lazy initialization you can instead just use a `namespace`: > Warning : Singleton is just a fancy name for [global](http://stackoverflow.com/a/142450/390330) For most projects `namespace` can additionally be replaced by a _module_. [Previousstatic constructors](https://basarat.gitbook.io/typescript/main-1/staticconstructor) [NextFunction parameters](https://basarat.gitbook.io/typescript/main-1/functionparameters) Last updated 5 years ago Copy namespace Singleton { // ... any one time initialization goes here ... export function someMethod() { } } // Usage Singleton.someMethod(); Copy // someFile.ts // ... any one time initialization goes here ... export function someMethod() { } // Usage import {someMethod} from "./someFile"; --- # JQuery tips | TypeScript Deep Dive Note: you need to install the `jquery.d.ts` file for these tips [](https://basarat.gitbook.io/typescript/main-1/jquery#quickly-define-a-new-plugin) Quickly define a new plugin -------------------------------------------------------------------------------------------------------------------- Just create `jquery-foo.d.ts` with: Copy interface JQuery { foo: any; } And now you can use `$('something').foo({whateverYouWant:'hello jquery plugin'})` [PreviousoutFile caution](https://basarat.gitbook.io/typescript/main-1/outfile) [Nextstatic constructors](https://basarat.gitbook.io/typescript/main-1/staticconstructor) Last updated 5 years ago --- # Type Compatibility | TypeScript Deep Dive * [Type Compatibility](https://basarat.gitbook.io/typescript/type-system/type-compatibility#type-compatibility) * [Soundness](https://basarat.gitbook.io/typescript/type-system/type-compatibility#soundness) * [Structural](https://basarat.gitbook.io/typescript/type-system/type-compatibility#structural) * [Generics](https://basarat.gitbook.io/typescript/type-system/type-compatibility#generics) * [Variance](https://basarat.gitbook.io/typescript/type-system/type-compatibility#variance) * [Functions](https://basarat.gitbook.io/typescript/type-system/type-compatibility#functions) * [Return Type](https://basarat.gitbook.io/typescript/type-system/type-compatibility#return-type) * [Number of arguments](https://basarat.gitbook.io/typescript/type-system/type-compatibility#number-of-arguments) * [Optional and rest parameters](https://basarat.gitbook.io/typescript/type-system/type-compatibility#optional-and-rest-parameters) * [Types of arguments](https://basarat.gitbook.io/typescript/type-system/type-compatibility#types-of-arguments) * [Enums](https://basarat.gitbook.io/typescript/type-system/type-compatibility#enums) * [Classes](https://basarat.gitbook.io/typescript/type-system/type-compatibility#classes) * [Generics](https://basarat.gitbook.io/typescript/type-system/type-compatibility#generics) * [FootNote: Invariance](https://basarat.gitbook.io/typescript/type-system/type-compatibility#footnote-invariance) [](https://basarat.gitbook.io/typescript/type-system/type-compatibility#type-compatibility) Type Compatibility ------------------------------------------------------------------------------------------------------------------- Type Compatibility (as we discuss here) determines if one thing can be assigned to another. E.g. `string` and `number` are not compatible: [](https://basarat.gitbook.io/typescript/type-system/type-compatibility#soundness) Soundness ------------------------------------------------------------------------------------------------- TypeScript's type system is designed to be convenient and allows for _unsound_ behaviours e.g. anything can be assigned to `any` which means telling the compiler to allow you to do whatever you want: [](https://basarat.gitbook.io/typescript/type-system/type-compatibility#structural) Structural --------------------------------------------------------------------------------------------------- TypeScript objects are structurally typed. This means the _names_ don't matter as long as the structures match This allows you to create objects on the fly (like you do in vanilla JS) and still have safety whenever it can be inferred. Also _more_ data is considered fine: [](https://basarat.gitbook.io/typescript/type-system/type-compatibility#variance) Variance ----------------------------------------------------------------------------------------------- Variance is an easy to understand and important concept for type compatibility analysis. For simple types `Base` and `Child`, if `Child` is a child of `Base`, then instances of `Child` can be assigned to a variable of type `Base`. > This is polymorphism 101 In type compatibility of complex types composed of such `Base` and `Child` types depends on where the `Base` and `Child` in similar scenarios is driven by _variance_. * Covariant : (co aka joint) only in _same direction_ * Contravariant : (contra aka negative) only in _opposite direction_ * Bivariant : (bi aka both) both co and contra. * Invariant : if the types aren't exactly the same then they are incompatible. > Note: For a completely sound type system in the presence of mutable data like JavaScript, `invariant` is the only valid option. But as mentioned _convenience_ forces us to make unsound choices. [](https://basarat.gitbook.io/typescript/type-system/type-compatibility#functions) Functions ------------------------------------------------------------------------------------------------- There are a few subtle things to consider when comparing two functions. ### [](https://basarat.gitbook.io/typescript/type-system/type-compatibility#return-type) Return Type `covariant`: The return type must contain at least enough data. ### [](https://basarat.gitbook.io/typescript/type-system/type-compatibility#number-of-arguments) Number of arguments Fewer arguments are okay (i.e. functions can choose to ignore additional parameters). After all you are guaranteed to be called with at least enough arguments. ### [](https://basarat.gitbook.io/typescript/type-system/type-compatibility#optional-and-rest-parameters) Optional and Rest Parameters Optional (pre determined count) and Rest parameters (any count of arguments) are compatible, again for convenience. > Note: optional (in our example `bar`) and non optional (in our example `foo`) are only compatible if strictNullChecks is false. ### [](https://basarat.gitbook.io/typescript/type-system/type-compatibility#types-of-arguments) Types of arguments `bivariant` : This is designed to support common event handling scenarios Also makes `Array` assignable to `Array` (covariance) as the functions are compatible. Array covariance requires all `Array` functions to be assignable to `Array` e.g. `push(t:Child)` is assignable to `push(t:Base)` which is made possible by function argument bivariance. **This can be confusing for people coming from other languages** who would expect the following to error but will not in TypeScript: [](https://basarat.gitbook.io/typescript/type-system/type-compatibility#enums) Enums ----------------------------------------------------------------------------------------- * Enums are compatible with numbers, and numbers are compatible with enums. * Enum values from different enum types are considered incompatible. This makes enums useable _nominally_ (as opposed to structurally) [](https://basarat.gitbook.io/typescript/type-system/type-compatibility#classes) Classes --------------------------------------------------------------------------------------------- * Only instance members and methods are compared. _constructors_ and _statics_ play no part. * `private` and `protected` members _must originate from the same class_. Such members essentially make the class _nominal_. [](https://basarat.gitbook.io/typescript/type-system/type-compatibility#generics) Generics ----------------------------------------------------------------------------------------------- Since TypeScript has a structural type system, type parameters only affect compatibility when used by a member. For example, in the following `T` has no impact on compatibility: However, if `T` is used, it will play a role in compatibility based on its _instantiation_ as shown below: In cases where generic arguments haven't been _instantiated_ they are substituted by `any` before checking compatibility: Generics involving classes are matched by relevant class compatibility as mentioned before. e.g. [](https://basarat.gitbook.io/typescript/type-system/type-compatibility#footnote-invariance) FootNote: Invariance ---------------------------------------------------------------------------------------------------------------------- We said invariance is the only sound option. Here is an example where both `contra` and `co` variance are shown to be unsafe for arrays. [PreviousType Inference](https://basarat.gitbook.io/typescript/type-system/type-inference) [NextNever Type](https://basarat.gitbook.io/typescript/type-system/never) Last updated 5 years ago * [Type Compatibility](https://basarat.gitbook.io/typescript/type-system/type-compatibility#type-compatibility) * [Soundness](https://basarat.gitbook.io/typescript/type-system/type-compatibility#soundness) * [Structural](https://basarat.gitbook.io/typescript/type-system/type-compatibility#structural) * [Variance](https://basarat.gitbook.io/typescript/type-system/type-compatibility#variance) * [Functions](https://basarat.gitbook.io/typescript/type-system/type-compatibility#functions) * [Return Type](https://basarat.gitbook.io/typescript/type-system/type-compatibility#return-type) * [Number of arguments](https://basarat.gitbook.io/typescript/type-system/type-compatibility#number-of-arguments) * [Optional and Rest Parameters](https://basarat.gitbook.io/typescript/type-system/type-compatibility#optional-and-rest-parameters) * [Types of arguments](https://basarat.gitbook.io/typescript/type-system/type-compatibility#types-of-arguments) * [Enums](https://basarat.gitbook.io/typescript/type-system/type-compatibility#enums) * [Classes](https://basarat.gitbook.io/typescript/type-system/type-compatibility#classes) * [Generics](https://basarat.gitbook.io/typescript/type-system/type-compatibility#generics) * [FootNote: Invariance](https://basarat.gitbook.io/typescript/type-system/type-compatibility#footnote-invariance) Copy let str: string = "Hello"; let num: number = 123; str = num; // ERROR: `number` is not assignable to `string` num = str; // ERROR: `string` is not assignable to `number` Copy let foo: any = 123; foo = "Hello"; // Later foo.toPrecision(3); // Allowed as you typed it as `any` Copy interface Point { x: number, y: number } class Point2D { constructor(public x:number, public y:number){} } let p: Point; // OK, because of structural typing p = new Point2D(1,2); Copy interface Point2D { x: number; y: number; } interface Point3D { x: number; y: number; z: number; } var point2D: Point2D = { x: 0, y: 10 } var point3D: Point3D = { x: 0, y: 10, z: 20 } function iTakePoint2D(point: Point2D) { /* do something */ } iTakePoint2D(point2D); // exact match okay iTakePoint2D(point3D); // extra information okay iTakePoint2D({ x: 0 }); // Error: missing information `y` Copy /** Type Hierarchy */ interface Point2D { x: number; y: number; } interface Point3D { x: number; y: number; z: number; } /** Two sample functions */ let iMakePoint2D = (): Point2D => ({ x: 0, y: 0 }); let iMakePoint3D = (): Point3D => ({ x: 0, y: 0, z: 0 }); /** Assignment */ iMakePoint2D = iMakePoint3D; // Okay iMakePoint3D = iMakePoint2D; // ERROR: Point2D is not assignable to Point3D Copy let iTakeSomethingAndPassItAnErr = (x: (err: Error, data: any) => void) => { /* do something */ }; iTakeSomethingAndPassItAnErr(() => null) // Okay iTakeSomethingAndPassItAnErr((err) => null) // Okay iTakeSomethingAndPassItAnErr((err, data) => null) // Okay // ERROR: Argument of type '(err: any, data: any, more: any) => null' is not assignable to parameter of type '(err: Error, data: any) => void'. iTakeSomethingAndPassItAnErr((err, data, more) => null); Copy let foo = (x:number, y: number) => { /* do something */ } let bar = (x?:number, y?: number) => { /* do something */ } let bas = (...args: number[]) => { /* do something */ } foo = bar = bas; bas = bar = foo; Copy /** Event Hierarchy */ interface Event { timestamp: number; } interface MouseEvent extends Event { x: number; y: number } interface KeyEvent extends Event { keyCode: number } /** Sample event listener */ enum EventType { Mouse, Keyboard } function addEventListener(eventType: EventType, handler: (n: Event) => void) { /* ... */ } // Unsound, but useful and common. Works as function argument comparison is bivariant addEventListener(EventType.Mouse, (e: MouseEvent) => console.log(e.x + "," + e.y)); // Undesirable alternatives in presence of soundness addEventListener(EventType.Mouse, (e: Event) => console.log((e).x + "," + (e).y)); addEventListener(EventType.Mouse, <(e: Event) => void>((e: MouseEvent) => console.log(e.x + "," + e.y))); // Still disallowed (clear error). Type safety enforced for wholly incompatible types addEventListener(EventType.Mouse, (e: number) => console.log(e)); Copy /** Type Hierarchy */ interface Point2D { x: number; y: number; } interface Point3D { x: number; y: number; z: number; } /** Two sample functions */ let iTakePoint2D = (point: Point2D) => { /* do something */ } let iTakePoint3D = (point: Point3D) => { /* do something */ } iTakePoint3D = iTakePoint2D; // Okay : Reasonable iTakePoint2D = iTakePoint3D; // Okay : WHAT Copy enum Status { Ready, Waiting }; let status = Status.Ready; let num = 0; status = num; // OKAY num = status; // OKAY Copy enum Status { Ready, Waiting }; enum Color { Red, Blue, Green }; let status = Status.Ready; let color = Color.Red; status = color; // ERROR Copy class Animal { feet: number; constructor(name: string, numFeet: number) { /** do something */ } } class Size { feet: number; constructor(meters: number) { /** do something */ } } let a: Animal; let s: Size; a = s; // OK s = a; // OK Copy /** A class hierarchy */ class Animal { protected feet: number; } class Cat extends Animal { } let animal: Animal; let cat: Cat; animal = cat; // OKAY cat = animal; // OKAY /** Looks just like Animal */ class Size { protected feet: number; } let size: Size; animal = size; // ERROR size = animal; // ERROR Copy interface Empty { } let x: Empty; let y: Empty; x = y; // okay, y matches structure of x Copy interface NotEmpty { data: T; } let x: NotEmpty; let y: NotEmpty; x = y; // error, x and y are not compatible Copy let identity = function(x: T): T { // ... } let reverse = function(y: U): U { // ... } identity = reverse; // Okay because (x: any)=>any matches (y: any)=>any Copy class List { add(val: T) { } } class Animal { name: string; } class Cat extends Animal { meow() { } } const animals = new List(); animals.add(new Animal()); // Okay animals.add(new Cat()); // Okay const cats = new List(); cats.add(new Animal()); // Error cats.add(new Cat()); // Okay Copy /** Hierarchy */ class Animal { constructor(public name: string){} } class Cat extends Animal { meow() { } } /** An item of each */ var animal = new Animal("animal"); var cat = new Cat("cat"); /** * Demo : polymorphism 101 * Animal <= Cat */ animal = cat; // Okay cat = animal; // ERROR: cat extends animal /** Array of each to demonstrate variance */ let animalArr: Animal[] = [animal]; let catArr: Cat[] = [cat]; /** * Obviously Bad : Contravariance * Animal <= Cat * Animal[] >= Cat[] */ catArr = animalArr; // Okay if contravariant catArr[0].meow(); // Allowed but BANG ๐Ÿ”ซ at runtime /** * Also Bad : covariance * Animal <= Cat * Animal[] <= Cat[] */ animalArr = catArr; // Okay if covariant animalArr.push(new Animal('another animal')); // Just pushed an animal into catArr! catArr.forEach(c => c.meow()); // Allowed but BANG ๐Ÿ”ซ at runtime --- # Type Instantiation | TypeScript Deep Dive Say you have something that has a generic parameter e.g. a class `Foo`: Copy class Foo{ foo: T; } You want to create a specialized version for it for a particular type. The pattern is to copy the item into a new variable and give it the type annotation with the generics replaced with concrete types. E.g. if you want a class `Foo`: Copy class Foo{ foo: T; } let FooNumber = Foo as { new ():Foo }; // ref 1 In `ref 1` you are saying that `FooNumber` is the same as `Foo` but just treat it as something that when called with the `new` operator gives an instance of `Foo`. [](https://basarat.gitbook.io/typescript/main-1/typeinstantiation#inheritance) Inheritance ----------------------------------------------------------------------------------------------- The Type assertion pattern is unsafe in that it trusts you to do the right thing. A common pattern in other languages _for classes_ is to just use inheritance : Copy class FooNumber extends Foo{} One word of caution here: if you use decorators on the base class then the inherited class might not have the same behavior as the base class (it is no longer wrapped by the decorator). Of course if you are not specializing classes you still have to come up with a coercion / assertion pattern that works and hence we showed the general assertion pattern first, e.g.: Copy function id(x: T) { return x; } const idNum = id as {(x:number):number}; > Inspired by this [stackoverflow question](http://stackoverflow.com/a/34864705/390330) [PreviousCurrying](https://basarat.gitbook.io/typescript/main-1/currying) [NextLazy Object Literal Initialization](https://basarat.gitbook.io/typescript/main-1/lazyobjectliteralinitialization) Last updated 5 years ago --- # Function parameters | TypeScript Deep Dive If you have a function that takes too many parameters, or parameters of the same type, then you might want to consider changing the function to take an object instead. Consider the following function: Copy function foo(flagA: boolean, flagB: boolean) { // your awesome function body } With such a function definition it's quite easy to invoke it incorrectly e.g. `foo(flagB, flagA)` and you would get no help from the compiler. Instead, convert the function to take an object: Copy function foo(config: {flagA: boolean, flagB: boolean}) { const {flagA, flagB} = config; // your awesome function body } Now the function calls will look like `foo({flagA, flagB})` which makes it much easier to spot mistakes and code review. > Note : If your function is simple enough, and you don't expect much churn, then feel free to ignore this advice ๐ŸŒน. [Previoussingleton pattern](https://basarat.gitbook.io/typescript/main-1/singleton) [NextBuild Toggles](https://basarat.gitbook.io/typescript/main-1/build-toggles) Last updated 5 years ago --- # Lazy Object Literal Initialization | TypeScript Deep Dive Quite commonly in JavaScript code bases you would initialize object literals in the following manner: Copy let foo = {}; foo.bar = 123; foo.bas = "Hello World"; As soon as you move the code to TypeScript you will start to get Errors like the following: Copy let foo = {}; foo.bar = 123; // Error: Property 'bar' does not exist on type '{}' foo.bas = "Hello World"; // Error: Property 'bas' does not exist on type '{}' This is because from the state `let foo = {}`, TypeScript _infers_ the type of `foo` (left hand side of initializing assignment) to be the type of the right hand side `{}` (i.e. an object with no properties). So, it error if you try to assign to a property it doesn't know about. [](https://basarat.gitbook.io/typescript/main-1/lazyobjectliteralinitialization#ideal-fix) Ideal Fix --------------------------------------------------------------------------------------------------------- The _proper_ way to initialize an object in TypeScript is to do it in the assignment: Copy let foo = { bar: 123, bas: "Hello World", }; This is also great for code review and code maintainability purposes. > The quick fix and middle ground _lazy_ initialization patterns described below suffer from _mistakenly forgetting to initialize a property_. [](https://basarat.gitbook.io/typescript/main-1/lazyobjectliteralinitialization#quick-fix) Quick Fix --------------------------------------------------------------------------------------------------------- If you have a large JavaScript code base that you are migrating to TypeScript the ideal fix might not be a viable solution for you. In that case you can carefully use a _type assertion_ to silence the compiler: [](https://basarat.gitbook.io/typescript/main-1/lazyobjectliteralinitialization#middle-ground) Middle Ground ----------------------------------------------------------------------------------------------------------------- Of course using the `any` assertion can be very bad as it sort of defeats the safety of TypeScript. The middle ground fix is to create an `interface` to ensure * Good Docs * Safe assignment This is shown below: Here is a quick example that shows the fact that using the interface can save you: [PreviousType Instantiation](https://basarat.gitbook.io/typescript/main-1/typeinstantiation) [NextClasses are Useful](https://basarat.gitbook.io/typescript/main-1/classesareuseful) Last updated 5 years ago * [Ideal Fix](https://basarat.gitbook.io/typescript/main-1/lazyobjectliteralinitialization#ideal-fix) * [Quick Fix](https://basarat.gitbook.io/typescript/main-1/lazyobjectliteralinitialization#quick-fix) * [Middle Ground](https://basarat.gitbook.io/typescript/main-1/lazyobjectliteralinitialization#middle-ground) Copy let foo = {} as any; foo.bar = 123; foo.bas = "Hello World"; Copy interface Foo { bar: number bas: string } let foo = {} as Foo; foo.bar = 123; foo.bas = "Hello World"; Copy interface Foo { bar: number bas: string } let foo = {} as Foo; foo.bar = 123; foo.bas = "Hello World"; // later in the codebase: foo.bar = 'Hello Stranger'; // Error: You probably misspelled `bas` as `bar`, cannot assign string to number --- # Create Arrays | TypeScript Deep Dive Creating an empty array is super easy: Copy const foo: string[] = []; If you want an array to loop over: Copy [...new Array(6)]; If you want to create an array pre-filled with some content use the ES6 `Array.prototype.fill`: Copy const foo: string[] = new Array(3).fill(''); console.log(foo); // ['','','']; If you want to create an array of a predefined length with calls you can use the spread operator: Copy const someNumbers = [...new Array(3)].map((_,i) => i * 10); console.log(someNumbers); // [0,10,20]; [PreviousBarrel](https://basarat.gitbook.io/typescript/main-1/barrel) [NextTypesafe Event Emitter](https://basarat.gitbook.io/typescript/main-1/typed-event) Last updated 3 years ago --- # Avoid Export Default | TypeScript Deep Dive Consider you have a file `foo.ts` with the following contents: Copy class Foo { } export default Foo; You would import it (in `bar.ts`) using ES6 syntax as follows: Copy import Foo from "./foo"; There are a few maintainability concerns here: * If you refactor `Foo` in `foo.ts` it will not rename it in `bar.ts`. * If you end up needing to export more stuff from `foo.ts` (which is what many of your files will have) then you have to juggle the import syntax. For this reason I recommend simple exports + destructured import. E.g. `foo.ts`: Copy export class Foo { } And then: Copy import { Foo } from "./foo"; Below I also present a few more reasons. [](https://basarat.gitbook.io/typescript/main-1/defaultisbad#poor-discoverability) Poor Discoverability ------------------------------------------------------------------------------------------------------------ Discoverability is very poor for default exports. You cannot explore a module with intellisense to see if it has a default export or not. With export default you get nothing here (maybe it does export default / maybe it doesn't `ยฏ\_(ใƒ„)_/ยฏ`): Without export default you get a nice intellisense here: [](https://basarat.gitbook.io/typescript/main-1/defaultisbad#autocomplete) Autocomplete -------------------------------------------------------------------------------------------- Irrespective of if you know about the exports, you even autocomplete at this `import {/*here*/} from "./foo";` cursor location. Gives your developers a bit of wrist relief. [](https://basarat.gitbook.io/typescript/main-1/defaultisbad#commonjs-interop) CommonJS interop ---------------------------------------------------------------------------------------------------- With `default` there is horrible experience for commonJS users who have to `const {default} = require('module/foo');` instead of `const {Foo} = require('module/foo')`. You will most likely want to rename the `default` export to something else when you import it. [](https://basarat.gitbook.io/typescript/main-1/defaultisbad#typo-protection) Typo Protection -------------------------------------------------------------------------------------------------- You don't get typos like one dev doing `import Foo from "./foo";` and another doing `import foo from "./foo";` [](https://basarat.gitbook.io/typescript/main-1/defaultisbad#typescript-auto-import) TypeScript auto-import ---------------------------------------------------------------------------------------------------------------- Auto import quickfix works better. You use `Foo` and auto import will write down `import { Foo } from "./foo";` cause its a well defined name exported from a module. Some tools out there will try to magic read and _infer_ a name for a default export but magic is flaky. [](https://basarat.gitbook.io/typescript/main-1/defaultisbad#re-exporting) Re-exporting -------------------------------------------------------------------------------------------- Re-exporting is common for the root `index` file in npm packages, and forces you to name the default export manually e.g. `export { default as Foo } from "./foo";` (with default) vs. `export * from "./foo"` (with named exports). [](https://basarat.gitbook.io/typescript/main-1/defaultisbad#dynamic-imports) Dynamic Imports -------------------------------------------------------------------------------------------------- Default exports expose themselves badly named as `default` in dynamic `import`s e.g. Much nicer with named exports: [](https://basarat.gitbook.io/typescript/main-1/defaultisbad#needs-two-lines-for-non-class-non-function) Needs two lines for non-class / non-function ---------------------------------------------------------------------------------------------------------------------------------------------------------- Can be one statement for function / class e.g. Can be one statement for _non named / type annotated_ objects e.g.: But needs two statements otherwise: [PreviousClasses are Useful](https://basarat.gitbook.io/typescript/main-1/classesareuseful) [NextLimit Property Setters](https://basarat.gitbook.io/typescript/main-1/propertysetters) Last updated 5 years ago * [Poor Discoverability](https://basarat.gitbook.io/typescript/main-1/defaultisbad#poor-discoverability) * [Autocomplete](https://basarat.gitbook.io/typescript/main-1/defaultisbad#autocomplete) * [CommonJS interop](https://basarat.gitbook.io/typescript/main-1/defaultisbad#commonjs-interop) * [Typo Protection](https://basarat.gitbook.io/typescript/main-1/defaultisbad#typo-protection) * [TypeScript auto-import](https://basarat.gitbook.io/typescript/main-1/defaultisbad#typescript-auto-import) * [Re-exporting](https://basarat.gitbook.io/typescript/main-1/defaultisbad#re-exporting) * [Dynamic Imports](https://basarat.gitbook.io/typescript/main-1/defaultisbad#dynamic-imports) * [Needs two lines for non-class / non-function](https://basarat.gitbook.io/typescript/main-1/defaultisbad#needs-two-lines-for-non-class-non-function) Copy import /* here */ from 'something'; Copy import { /* here */ } from 'something'; Copy const HighCharts = await import('https://code.highcharts.com/js/es-modules/masters/highcharts.src.js'); HighCharts.default.chart('container', { ... }); // Notice `.default` Copy const {HighCharts} = await import('https://code.highcharts.com/js/es-modules/masters/highcharts.src.js'); HighCharts.chart('container', { ... }); // Notice `.default` Copy export default function foo() { } Copy export default { notAFunction: 'Yeah, I am not a function or a class', soWhat: 'The export is now *removed* from the declaration' }; Copy // If you need to name it (here `foo`) for local use OR need to annotate type (here `Foo`) const foo: Foo = { notAFunction: 'Yeah, I am not a function or a class', soWhat: 'The export is now *removed* from the declaration' }; export default foo; --- # Classes are Useful | TypeScript Deep Dive It is very common to have the following structure: Copy function foo() { let someProperty; // Some other initialization code function someMethod() { // Do some stuff with `someProperty` // And potentially other things } // Maybe some other methods return { someMethod, // Maybe some other methods }; } This is known as the _revealing module pattern_ and quite common in JavaScript (taking advantage of JavaScript closure). If you use [_file modules_ (which you really should as global scope is bad)](https://basarat.gitbook.io/typescript/project/modules) then _your file is effectively the same_. However, there are too many cases where people will write code like the following: Copy let someProperty; function foo() { // Some initialization code } foo(); // some initialization code someProperty = 123; // some more initialization // Some utility function not exported // later export function someMethod() { } Even though I am not a big fan of inheritance _I do find that letting people use classes helps them organize their code better_. The same developer would intuitively write the following: And its not just developers, creating dev tools that provide great visualizations over classes are much more common, and there is one less pattern your team needs to understand and maintain. > PS: There is nothing wrong in my opinion with _shallow_ class hierarchies if they provide significant reuse and reduction in boiler plate. [PreviousLazy Object Literal Initialization](https://basarat.gitbook.io/typescript/main-1/lazyobjectliteralinitialization) [NextAvoid Export Default](https://basarat.gitbook.io/typescript/main-1/defaultisbad) Last updated 5 years ago Copy class Foo { public someProperty; constructor() { // some initialization } public someMethod() { // some code } private someUtility() { // some code } } export = new Foo(); --- # Barrel | TypeScript Deep Dive A barrel is a way to rollup exports from several modules into a single convenient module. The barrel itself is a module file that re-exports selected exports of other modules. Imagine the following class structure in a library: Copy // demo/foo.ts export class Foo {} // demo/bar.ts export class Bar {} // demo/baz.ts export class Baz {} Without a barrel, a consumer would need three import statements: Copy import { Foo } from '../demo/foo'; import { Bar } from '../demo/bar'; import { Baz } from '../demo/baz'; You can instead add a barrel `demo/index.ts` containing the following: Copy // demo/index.ts export * from './foo'; // re-export all of its exports export * from './bar'; // re-export all of its exports export * from './baz'; // re-export all of its exports Now the consumer can import what it needs from the barrel: [](https://basarat.gitbook.io/typescript/main-1/barrel#named-exports) Named exports ---------------------------------------------------------------------------------------- Instead of exporting `*`, you can choose to export the module in a name. E.g., assume that `baz.ts` has functions: If you would rather not export `getBaz` / `setBaz` from demo you can instead put them in a variable by importing them in a name and exporting that name as shown below: And now the consumer would look like: [PreviousBuild Toggles](https://basarat.gitbook.io/typescript/main-1/build-toggles) [NextCreate Arrays](https://basarat.gitbook.io/typescript/main-1/create-arrays) Last updated 5 years ago Copy import { Foo, Bar, Baz } from '../demo'; // demo/index.ts is implied Copy // demo/foo.ts export class Foo {} // demo/bar.ts export class Bar {} // demo/baz.ts export function getBaz() {} export function setBaz() {} Copy // demo/index.ts export * from './foo'; // re-export all of its exports export * from './bar'; // re-export all of its exports import * as baz from './baz'; // import as a name export { baz }; // export the name Copy import { Foo, Bar, baz } from '../demo'; // demo/index.ts is implied // usage baz.getBaz(); baz.setBaz(); // etc. ... --- # Program | TypeScript Deep Dive Defined in `program.ts`. The compilation context ([a concept we covered previously](https://basarat.gitbook.io/typescript/project/compilation-context) ) is represented within the TypeScript compiler as a `Program`. It consists of `SourceFile`s and compiler options. [](https://basarat.gitbook.io/typescript/overview/program#usage-of-compilerhost) Usage of `CompilerHost` ------------------------------------------------------------------------------------------------------------- Its interaction mechanism with the OE: `Program` _\-uses->_ `CompilerHost` _\-uses->_ `System` The reason for having a `CompilerHost` as a point of indirection is that it allows its interface to be more finely tuned for `Program` needs and not bother with OE needs (e.g. the `Program` doesn't care about `fileExists` a function provided by `System`). There are other users of `System` as well (e.g. tests). [](https://basarat.gitbook.io/typescript/overview/program#sourcefile) SourceFile ------------------------------------------------------------------------------------- The program provides an API to get the Source Files `getSourceFiles(): SourceFile[];`. Each is represented as a root-level node for an AST (called `SourceFile`). [PreviousTypeScript Compiler Internals](https://basarat.gitbook.io/typescript/overview) [NextAST](https://basarat.gitbook.io/typescript/overview/ast) Last updated 5 years ago * [Usage of CompilerHost](https://basarat.gitbook.io/typescript/overview/program#usage-of-compilerhost) * [SourceFile](https://basarat.gitbook.io/typescript/overview/program#sourcefile) --- # Jest | TypeScript Deep Dive > [Pro egghead lesson on Jest / TypeScript](https://egghead.io/lessons/typescript-getting-started-with-jest-using-typescript) No testing solution out there is perfect. That said, jest is an excellent unit testing option which provides great TypeScript support. > Note: We assume you start off with a simple node package.json setup. Also all TypeScript files should be in a `src` folder which is always recommended (even without Jest) for a clean project setup. [](https://basarat.gitbook.io/typescript/intro-1/jest#step-1-install) Step 1: Install ------------------------------------------------------------------------------------------ Install the following using npm: Copy npm i jest @types/jest ts-jest typescript -D Explanation: * Install `jest` framework (`jest`) * Install the types for `jest` (`@types/jest`) * Install the TypeScript preprocessor for jest (`ts-jest`) which allows jest to transpile TypeScript on the fly and have source-map support built in. * Install the TypeScript compiler ('typescript') which is prerequisite for 'ts-jest'. * Save all of these to your dev dependencies (testing is almost always a npm dev-dependency) [](https://basarat.gitbook.io/typescript/intro-1/jest#step-2-configure-jest) Step 2: Configure Jest -------------------------------------------------------------------------------------------------------- Add the following `jest.config.js` file to the root of your project: Copy module.exports = { "roots": [\ "/src"\ ], "testMatch": [\ "**/__tests__/**/*.+(ts|tsx|js)",\ "**/?(*.)+(spec|test).+(ts|tsx|js)"\ ], "transform": { "^.+\\.(ts|tsx)$": "ts-jest" }, } (If your `package.json` file contains `"type": "module"`, which causes Node to assume modules are in es6 format, you can convert the above to es6 format by replacing the top line to `export default {` .) Explanation: * We always recommend having _all_ TypeScript files in a `src` folder in your project. We assume this is true and specify this using the `roots` option. * The `testMatch` config is a glob pattern matcher for discovering .test / .spec files in ts / tsx / js format. * The `transform` config just tells `jest` to use `ts-jest` for ts / tsx files. [](https://basarat.gitbook.io/typescript/intro-1/jest#step-3-run-tests) Step 3: Run tests ---------------------------------------------------------------------------------------------- Run `npx jest` from your project root and jest will execute any tests you have. ### [](https://basarat.gitbook.io/typescript/intro-1/jest#optional-add-script-target-for-npm-scripts) Optional: Add script target for npm scripts Add `package.json`: * This allows you to run the tests with a simple `npm t`. * And even in watch mode with `npm t -- --watch`. ### [](https://basarat.gitbook.io/typescript/intro-1/jest#optional-run-jest-in-watch-mode) Optional: Run jest in watch mode * `npx jest --watch` ### [](https://basarat.gitbook.io/typescript/intro-1/jest#example) Example * For a file `foo.ts`: * A simple `foo.test.ts`: Notes: * Jest provides the global `test` function. * Jest comes prebuilt with assertions in the form of the global `expect`. ### [](https://basarat.gitbook.io/typescript/intro-1/jest#example-async) Example async Jest has built-in async/await support. e.g. ### [](https://basarat.gitbook.io/typescript/intro-1/jest#example-enzyme) Example enzyme > [Pro egghead lesson on Enzyme / Jest / TypeScript](https://egghead.io/lessons/react-test-react-components-and-dom-using-enzyme) Enzyme allows you to test react components with dom support. There are three steps to setting up enzyme: 1. Install enzyme, types for enzyme, a better snapshot serializer for enzyme, enzyme-adapter-react for your react version `npm i enzyme @types/enzyme enzyme-to-json enzyme-adapter-react-16 -D` 2. Add `"snapshotSerializers"` and `"setupTestFrameworkScriptFile"` to your `jest.config.js`: 3. Create `src/setupEnzyme.ts` file. Now here is an example react component and test: * `checkboxWithLabel.tsx`: * `checkboxWithLabel.test.tsx`: [](https://basarat.gitbook.io/typescript/intro-1/jest#reasons-why-we-like-jest) Reasons why we like jest ------------------------------------------------------------------------------------------------------------- > [For details on these features see jest website](http://facebook.github.io/jest/) * Built-in assertion library. * Great TypeScript support. * Very reliable test watcher. * Snapshot testing. * Built-in coverage reports. * Built-in async/await support. [PreviousTesting](https://basarat.gitbook.io/typescript/intro-1) [NextCypress](https://basarat.gitbook.io/typescript/intro-1/cypress) Last updated 5 years ago * [Step 1: Install](https://basarat.gitbook.io/typescript/intro-1/jest#step-1-install) * [Step 2: Configure Jest](https://basarat.gitbook.io/typescript/intro-1/jest#step-2-configure-jest) * [Step 3: Run tests](https://basarat.gitbook.io/typescript/intro-1/jest#step-3-run-tests) * [Optional: Add script target for npm scripts](https://basarat.gitbook.io/typescript/intro-1/jest#optional-add-script-target-for-npm-scripts) * [Optional: Run jest in watch mode](https://basarat.gitbook.io/typescript/intro-1/jest#optional-run-jest-in-watch-mode) * [Example](https://basarat.gitbook.io/typescript/intro-1/jest#example) * [Example async](https://basarat.gitbook.io/typescript/intro-1/jest#example-async) * [Example enzyme](https://basarat.gitbook.io/typescript/intro-1/jest#example-enzyme) * [Reasons why we like jest](https://basarat.gitbook.io/typescript/intro-1/jest#reasons-why-we-like-jest) Copy { "test": "jest" } Copy export const sum = (...a: number[]) => a.reduce((acc, val) => acc + val, 0); Copy import { sum } from '../foo'; test('basic', () => { expect(sum()).toBe(0); }); test('basic again', () => { expect(sum(1, 2)).toBe(3); }); Copy test('basic',async () => { expect(sum()).toBe(0); }); test('basic again', async () => { expect(sum(1, 2)).toBe(3); }, 1000 /* optional timeout */); Copy module.exports = { // OTHER PORTIONS AS MENTIONED BEFORE // Setup Enzyme "snapshotSerializers": ["enzyme-to-json/serializer"], "setupFilesAfterEnv": ["/src/setupEnzyme.ts"], } Copy import { configure } from 'enzyme'; import EnzymeAdapter from 'enzyme-adapter-react-16'; configure({ adapter: new EnzymeAdapter() }); Copy import * as React from 'react'; export class CheckboxWithLabel extends React.Component<{ labelOn: string, labelOff: string }, { isChecked: boolean }> { constructor(props) { super(props); this.state = { isChecked: false }; } onChange = () => { this.setState({ isChecked: !this.state.isChecked }); } render() { return ( ); } } Copy import * as React from 'react'; import { shallow } from 'enzyme'; import { CheckboxWithLabel } from './checkboxWithLabel'; test('CheckboxWithLabel changes the text after click', () => { const checkbox = shallow(); // Interaction demo expect(checkbox.text()).toEqual('Off'); checkbox.find('input').simulate('change'); expect(checkbox.text()).toEqual('On'); // Snapshot demo expect(checkbox).toMatchSnapshot(); }); --- # Checker Error Reporting | TypeScript Deep Dive The checker uses the local `error` function to report errors. Here is the function: Copy function error(location: Node, message: DiagnosticMessage, arg0?: any, arg1?: any, arg2?: any): void { let diagnostic = location ? createDiagnosticForNode(location, message, arg0, arg1, arg2) : createCompilerDiagnostic(message, arg0, arg1, arg2); diagnostics.add(diagnostic); } [PreviousChecker Diagnostics](https://basarat.gitbook.io/typescript/overview/checker/checker-global) [NextEmitter](https://basarat.gitbook.io/typescript/overview/emitter) Last updated 5 years ago --- # Typesafe Event Emitter | TypeScript Deep Dive Conventionally in Node.js and traditional JavaScript you have a single event emitter. This event emitter internally tracks listener for different event types e.g. Copy const emitter = new EventEmitter(); // Emit: emitter.emit('foo', foo); emitter.emit('bar', bar); // Listen: emitter.on('foo', (foo)=>console.log(foo)); emitter.on('bar', (bar)=>console.log(bar)); Essentially `EventEmitter` internally stores data in the form of mapped arrays: Copy {foo: [fooListeners], bar: [barListeners]} Instead, for the sake of _event_ type safety, you can create an emitter _per_ event type: Copy const onFoo = new TypedEvent(); const onBar = new TypedEvent(); // Emit: onFoo.emit(foo); onBar.emit(bar); // Listen: onFoo.on((foo)=>console.log(foo)); onBar.on((bar)=>console.log(bar)); This has the following advantages: * The types of events are easily discoverable as variables. * The event emitter variables are easily refactored independently. * Type safety for event data structures. [](https://basarat.gitbook.io/typescript/main-1/typed-event#reference-typedevent) Reference TypedEvent ----------------------------------------------------------------------------------------------------------- [PreviousCreate Arrays](https://basarat.gitbook.io/typescript/main-1/create-arrays) [NextStyleGuide](https://basarat.gitbook.io/typescript/styleguide) Last updated 5 years ago Copy export interface Listener { (event: T): any; } export interface Disposable { dispose(); } /** passes through events as they happen. You will not get events from before you start listening */ export class TypedEvent { private listeners: Listener[] = []; private listenersOncer: Listener[] = []; on = (listener: Listener): Disposable => { this.listeners.push(listener); return { dispose: () => this.off(listener) }; } once = (listener: Listener): void => { this.listenersOncer.push(listener); } off = (listener: Listener) => { var callbackIndex = this.listeners.indexOf(listener); if (callbackIndex > -1) this.listeners.splice(callbackIndex, 1); } emit = (event: T) => { /** Update any general listeners */ this.listeners.forEach((listener) => listener(event)); /** Clear the `once` queue */ if (this.listenersOncer.length > 0) { const toCall = this.listenersOncer; this.listenersOncer = []; toCall.forEach((listener) => listener(event)); } } pipe = (te: TypedEvent): Disposable => { return this.on((e) => te.emit(e)); } } --- # Checker Diagnostics | TypeScript Deep Dive Within `initializeTypeChecker` the following code exists: Copy // Initialize global symbol table forEach(host.getSourceFiles(), file => { if (!isExternalModule(file)) { mergeSymbolTable(globals, file.locals); } }); Which basically merges all the `global` symbols into the `let globals: SymbolTable = {};` (in `createTypeChecker`) SymbolTable. `mergeSymbolTable` primarily calls `mergeSymbol`. [PreviousChecker](https://basarat.gitbook.io/typescript/overview/checker) [NextChecker Error Reporting](https://basarat.gitbook.io/typescript/overview/checker/checker-diagnostics) Last updated 5 years ago --- # Nominal Typing | TypeScript Deep Dive [](https://basarat.gitbook.io/typescript/main-1/nominaltyping#nominal-typing) Nominal Typing ------------------------------------------------------------------------------------------------- The TypeScript type system is structural [and this is one of the main motivating benefits](https://basarat.gitbook.io/typescript/getting-started/why-typescript) . However, there are real-world use cases for a system where you want two variables to be differentiated because they have a different _type name_ even if they have the same structure. A very common use case is _identity_ structures (which are generally just strings with semantics associated with their _name_ in languages like C#/Java). There are a few patterns that have emerged in the community. I cover them in decreasing order of personal preference: [](https://basarat.gitbook.io/typescript/main-1/nominaltyping#using-literal-types) Using literal types ----------------------------------------------------------------------------------------------------------- This pattern uses generics and literal types: Copy /** Generic Id type */ type Id = { type: T, value: string, } /** Specific Id types */ type FooId = Id<'foo'>; type BarId = Id<'bar'>; /** Optional: constructors functions */ const createFoo = (value: string): FooId => ({ type: 'foo', value }); const createBar = (value: string): BarId => ({ type: 'bar', value }); let foo = createFoo('sample') let bar = createBar('sample'); foo = bar; // Error foo = foo; // Okay * Advantages * No need for any type assertions * Disadvantage * The structure `{type,value}` might not be desireable and need server serialization support [](https://basarat.gitbook.io/typescript/main-1/nominaltyping#using-enums) Using Enums ------------------------------------------------------------------------------------------- [Enums in TypeScript](https://basarat.gitbook.io/typescript/type-system/enums) offer a certain level of nominal typing. Two enum types aren't equal if they differ by name. We can use this fact to provide nominal typing for types that are otherwise structurally compatible. The workaround involves: * Creating a _brand_ enum. * Creating the type as an _intersection_ (`&`) of the brand enum + the actual structure. This is demonstrated below where the structure of the types is just a string: Note how the brand enums, `FooIdBrand` and `BarIdBrand` above, each have single member (`_`) that maps to the empty string, as specified by `{ _ = "" }`. This forces TypeScript to infer that these are string-based enums, with values of type `string`, and not enums with values of type `number`. This is necessary because TypeScript infers an empty enum (`{}`) to be a numeric enum, and as of TypeScript 3.6.2 the intersection of a numeric `enum` and `string` is `never`. [](https://basarat.gitbook.io/typescript/main-1/nominaltyping#using-interfaces) Using Interfaces ----------------------------------------------------------------------------------------------------- Because `numbers` are type compatible with `enum`s the previous technique cannot be used for them. Instead we can use interfaces to break the structural compatibility. This method is still used by the TypeScript compiler team, so worth mentioning. Using `_` prefix and a `Brand` suffix is a convention I strongly recommend (and [the one followed by the TypeScript team](https://github.com/Microsoft/TypeScript/blob/7b48a182c05ea4dea81bab73ecbbe9e013a79e99/src/compiler/types.ts#L693-L698) ). The workaround involves the following: * adding an unused property on a type to break structural compatibility. * using a type assertion when needing to new up or cast down. This is demonstrated below: [PreviousString Based Enums](https://basarat.gitbook.io/typescript/main-1/stringenums) [NextStateful Functions](https://basarat.gitbook.io/typescript/main-1/statefulfunctions) Last updated 5 years ago * [Nominal Typing](https://basarat.gitbook.io/typescript/main-1/nominaltyping#nominal-typing) * [Using literal types](https://basarat.gitbook.io/typescript/main-1/nominaltyping#using-literal-types) * [Using Enums](https://basarat.gitbook.io/typescript/main-1/nominaltyping#using-enums) * [Using Interfaces](https://basarat.gitbook.io/typescript/main-1/nominaltyping#using-interfaces) Copy // FOO enum FooIdBrand { _ = "" }; type FooId = FooIdBrand & string; // BAR enum BarIdBrand { _ = "" }; type BarId = BarIdBrand & string; /** * Usage Demo */ var fooId: FooId; var barId: BarId; // Safety! fooId = barId; // error barId = fooId; // error // Newing up fooId = 'foo' as FooId; barId = 'bar' as BarId; // Both types are compatible with the base var str: string; str = fooId; str = barId; Copy // FOO interface FooId extends String { _fooIdBrand: string; // To prevent type errors } // BAR interface BarId extends String { _barIdBrand: string; // To prevent type errors } /** * Usage Demo */ var fooId: FooId; var barId: BarId; // Safety! fooId = barId; // error barId = fooId; // error fooId = barId; // error barId = fooId; // error // Newing up fooId = 'foo' as any; barId = 'bar' as any; // If you need the base string var str: string; str = fooId as any; str = barId as any; --- # Emitter | TypeScript Deep Dive There are two `emitters` provided with the TypeScript compiler: * `emitter.ts`: this is the emitter you are most likely to be interested in. Its the TS -> JavaScript emitter. * `declarationEmitter.ts`: this is the emitter used to create a _declaration file_ (a `.d.ts`) for a _TypeScript source file_ (a `.ts` file). We will look at `emitter.ts` in this section. [](https://basarat.gitbook.io/typescript/overview/emitter#usage-by-program) Usage by `program` --------------------------------------------------------------------------------------------------- Program provides an `emit` function. This function primarily delegates to `emitFiles` function in `emitter.ts`. Here is the call stack: Copy Program.emit -> `emitWorker` (local in program.ts createProgram) -> `emitFiles` (function in emitter.ts) One thing that the `emitWorker` provides to the emitter (via an argument to `emitFiles`) is an `EmitResolver`. `EmitResolver` is provided by the program's TypeChecker, basically it is a subset of _local_ functions from `createChecker`. [PreviousChecker Error Reporting](https://basarat.gitbook.io/typescript/overview/checker/checker-diagnostics) [NextEmitter Functions](https://basarat.gitbook.io/typescript/overview/emitter/emitter-functions) Last updated 5 years ago --- # AST | TypeScript Deep Dive [](https://basarat.gitbook.io/typescript/overview/ast#node) Node --------------------------------------------------------------------- The basic building block of the Abstract Syntax Tree (AST). In general a `Node` represents non-terminals in the language grammar; however, some terminals are kept in the tree such as identifiers and literals. Two key things make up an AST node's documentation. The node's `SyntaxKind` which identifies its type within the AST, and its `interface`, the API the node provides when instantiated into the AST. Here are a few key `interface Node` members: * `TextRange` members that identify the node's `start` and `end` in the source file. * `parent?: Node` the parent of the node in the AST. There are other additional members for `Node` flags and modifiers etc. that you can lookup by searching `interface Node` in the source code but the ones we mentioned are vital for node traversal. [](https://basarat.gitbook.io/typescript/overview/ast#sourcefile) SourceFile --------------------------------------------------------------------------------- * `SyntaxKind.SourceFile` * `interface SourceFile`. Each `SourceFile` is a top-level AST node that is contained in the `Program`. [PreviousProgram](https://basarat.gitbook.io/typescript/overview/program) [NextTIP: Visit Children](https://basarat.gitbook.io/typescript/overview/ast/ast-tip-children) Last updated 5 years ago * [Node](https://basarat.gitbook.io/typescript/overview/ast#node) * [SourceFile](https://basarat.gitbook.io/typescript/overview/ast#sourcefile) --- # Parser Functions | TypeScript Deep Dive [](https://basarat.gitbook.io/typescript/overview/parser/parser-functions#parser-functions) Parser Functions ----------------------------------------------------------------------------------------------------------------- As mentioned `parseSourceFile` sets up the initial state and passes the work onto `parseSourceFileWorker` function. ### [](https://basarat.gitbook.io/typescript/overview/parser/parser-functions#parsesourcefileworker) `parseSourceFileWorker` Starts by creating a `SourceFile` AST node. Then it goes into parsing source code starting from the `parseStatements` function. Once that returns, it then completes the `SourceFile` node with additional information such as its `nodeCount`, `identifierCount` and such. ### [](https://basarat.gitbook.io/typescript/overview/parser/parser-functions#parsestatements) `parseStatements` One of the most significant `parseFoo` style functions (a concept we cover next). It switches by the current `token` returned from the scanner. E.g. if the current token is a `SemicolonToken` it will call out to `parseEmptyStatement` to create an AST node for an empty statement. [](https://basarat.gitbook.io/typescript/overview/parser/parser-functions#node-creation) Node creation ----------------------------------------------------------------------------------------------------------- The parser has a bunch of `parserFoo` functions with bodies that create `Foo` nodes. These are generally called (from other parser functions) at a time where a `Foo` node is expected. A typical sample of this process is the `parseEmptyStatement()` function which is used to parse out empty statements like `;;;;;;`. Here is the function in its entirety Copy function parseEmptyStatement(): Statement { let node = createNode(SyntaxKind.EmptyStatement); parseExpected(SyntaxKind.SemicolonToken); return finishNode(node); } It shows three critical functions `createNode`, `parseExpected` and `finishNode`. ### [](https://basarat.gitbook.io/typescript/overview/parser/parser-functions#createnode) `createNode` The parser's `createNode` function `function createNode(kind: SyntaxKind, pos?: number): Node` is responsible for creating a Node, setting up its `SyntaxKind` as passed in, and set the initial position if passed in (or use the position from the current scanner state). ### [](https://basarat.gitbook.io/typescript/overview/parser/parser-functions#parseexpected) `parseExpected` The parser's `parseExpected` function `function parseExpected(kind: SyntaxKind, diagnosticMessage?: DiagnosticMessage): boolean` will check that the current token in the parser state matches the desired `SyntaxKind`. If not it will either report the `diagnosticMessage` sent in or create a generic one of the form `foo expected`. It internally uses the `parseErrorAtPosition` function (which uses the scanning positions) to give good error reporting. [](https://basarat.gitbook.io/typescript/overview/parser/parser-functions#finishnode) `finishNode` ------------------------------------------------------------------------------------------------------- The parser's `finishNode` function `function finishNode(node: T, end?: number): T` sets up the `end` position for the node and additional useful stuff like the `parserContextFlags` it was parsed under as well as if there were any errors before parsing this node (if there were then we cannot reuse this AST node in incremental parsing). [PreviousParser](https://basarat.gitbook.io/typescript/overview/parser) [NextBinder](https://basarat.gitbook.io/typescript/overview/binder) Last updated 5 years ago * [Parser Functions](https://basarat.gitbook.io/typescript/overview/parser/parser-functions#parser-functions) * [parseSourceFileWorker](https://basarat.gitbook.io/typescript/overview/parser/parser-functions#parsesourcefileworker) * [parseStatements](https://basarat.gitbook.io/typescript/overview/parser/parser-functions#parsestatements) * [Node creation](https://basarat.gitbook.io/typescript/overview/parser/parser-functions#node-creation) * [createNode](https://basarat.gitbook.io/typescript/overview/parser/parser-functions#createnode) * [parseExpected](https://basarat.gitbook.io/typescript/overview/parser/parser-functions#parseexpected) * [finishNode](https://basarat.gitbook.io/typescript/overview/parser/parser-functions#finishnode) --- # Declaration Files | TypeScript Deep Dive You can tell TypeScript that you are trying to describe code that exists elsewhere (e.g. written in JavaScript/CoffeeScript/The runtime environment like the browser or Node.js) using the `declare` keyword. As a quick example: Copy foo = 123; // Error: `foo` is not defined vs. Copy declare var foo: any; foo = 123; // allowed You have the option of putting these declarations in a `.ts` file or in a `.d.ts` file. We highly recommend that in your real world projects you use a separate `.d.ts` (start with one called something like `global.d.ts` or `vendor.d.ts`). If a file has the extension `.d.ts` then each root level definition must have the `declare` keyword prefixed to it. This helps make it clear to the author that there will be _no code emitted by TypeScript_. The author needs to ensure that the declared item will exist at runtime. > * Ambient declarations is a promise that you are making with the compiler. If these do not exist at runtime and you try to use them, things will break without warning. > > * Ambient declarations are like docs. If the source changes the docs need to be kept updated. So you might have new behaviours that work at runtime but no one's updated the ambient declaration and hence you get compiler errors. > [PreviousAmbient Declarations](https://basarat.gitbook.io/typescript/type-system/intro) [NextVariables](https://basarat.gitbook.io/typescript/type-system/intro/variables) Last updated 5 years ago --- # TIP: Visit Children | TypeScript Deep Dive There is a utility function `ts.forEachChild` that allows you to visit all the child nodes of any Node in the AST. Here is simplified snippet of the source code to demonstrate how it functions: Copy export function forEachChild(node: Node, cbNode: (node: Node) => T, cbNodeArray?: (nodes: Node[]) => T): T { if (!node) { return; } switch (node.kind) { case SyntaxKind.BinaryExpression: return visitNode(cbNode, (node).left) || visitNode(cbNode, (node).operatorToken) || visitNode(cbNode, (node).right); case SyntaxKind.IfStatement: return visitNode(cbNode, (node).expression) || visitNode(cbNode, (node).thenStatement) || visitNode(cbNode, (node).elseStatement); // .... lots more Basically, it checks `node.kind` and based on that assumes an interface offered by the `node` and calls the `cbNode` on the children. However, note that this function doesn't call `visitNode` for _all_ children (e.g. SyntaxKind.SemicolonToken). If you want _all_ the children of a node in the AST just call `.getChildren` member function of the `Node`. E.g. here is a function that prints the verbose `AST` of a node: Copy function printAllChildren(node: ts.Node, depth = 0) { console.log(new Array(depth+1).join('----'), ts.syntaxKindToName(node.kind), node.pos, node.end); depth++; node.getChildren().forEach(c=> printAllChildren(c, depth)); } We will see a sample usage of this function when we discuss the parser further. [PreviousAST](https://basarat.gitbook.io/typescript/overview/ast) [NextTIP: SyntaxKind enum](https://basarat.gitbook.io/typescript/overview/ast/ast-tip-syntaxkind) Last updated 5 years ago --- # Emitter SourceMaps | TypeScript Deep Dive We said that the bulk of the `emitter.ts` is the local function `emitJavaScript` (we showed the initialization routine of this function before). It basically sets up a bunch of locals and hits off to `emitSourceFile`. The following is a revisiting of the function, this time focusing on `SourceMap` stuff: Copy function emitJavaScript(jsFilePath: string, root?: SourceFile) { // STUFF ........... removed let writeComment = writeCommentRange; /** Write emitted output to disk */ let writeEmittedFiles = writeJavaScriptFile; /** Emit a node */ let emit = emitNodeWithoutSourceMap; /** Called just before starting emit of a node */ let emitStart = function (node: Node) { }; /** Called once the emit of the node is done */ let emitEnd = function (node: Node) { }; /** Emit the text for the given token that comes after startPos * This by default writes the text provided with the given tokenKind * but if optional emitFn callback is provided the text is emitted using the callback instead of default text * @param tokenKind the kind of the token to search and emit * @param startPos the position in the source to start searching for the token * @param emitFn if given will be invoked to emit the text instead of actual token emit */ let emitToken = emitTokenText; /** Called to before starting the lexical scopes as in function/class in the emitted code because of node * @param scopeDeclaration node that starts the lexical scope * @param scopeName Optional name of this scope instead of deducing one from the declaration node */ let scopeEmitStart = function(scopeDeclaration: Node, scopeName?: string) { }; /** Called after coming out of the scope */ let scopeEmitEnd = function() { }; /** Sourcemap data that will get encoded */ let sourceMapData: SourceMapData; if (compilerOptions.sourceMap || compilerOptions.inlineSourceMap) { initializeEmitterWithSourceMaps(); } if (root) { // Do not call emit directly. It does not set the currentSourceFile. emitSourceFile(root); } else { forEach(host.getSourceFiles(), sourceFile => { if (!isExternalModuleOrDeclarationFile(sourceFile)) { emitSourceFile(sourceFile); } }); } writeLine(); writeEmittedFiles(writer.getText(), /*writeByteOrderMark*/ compilerOptions.emitBOM); return; /// BUNCH OF LOCAL FUNCTIONS The important function call here : `initializeEmitterWithSourceMaps` which is a function local to `emitJavaScript` that overrides some locals that were already defined here. At the bottom of `initializeEmitterWithSourceMaps` you will notice the overriding: This means that the bulk of emitter code can not care about `SourceMap` and just use these local functions the same way with or without SourceMaps. [PreviousEmitter Functions](https://basarat.gitbook.io/typescript/overview/emitter/emitter-functions) [NextContributing](https://basarat.gitbook.io/typescript/overview/contributing) Last updated 5 years ago Copy // end of `initializeEmitterWithSourceMaps` writeEmittedFiles = writeJavaScriptAndSourceMapFile; emit = emitNodeWithSourceMap; emitStart = recordEmitNodeStartSpan; emitEnd = recordEmitNodeEndSpan; emitToken = writeTextWithSpanRecord; scopeEmitStart = recordScopeNameOfNode; scopeEmitEnd = recordScopeNameEnd; writeComment = writeCommentRangeWithMap; --- # Contributing | TypeScript Deep Dive TypeScript is [OSS and on GitHub](https://github.com/Microsoft/TypeScript) and the team welcomes community input. [](https://basarat.gitbook.io/typescript/overview/contributing#setup) Setup -------------------------------------------------------------------------------- Super easy: Copy git clone https://github.com/Microsoft/TypeScript.git cd TypeScript npm install -g jake npm install [](https://basarat.gitbook.io/typescript/overview/contributing#setup-fork) Setup Fork ------------------------------------------------------------------------------------------ You would obviously need to setup Microsoft/TypeScript as an `upstream` remote and your own _fork_ (use the GitHub _fork_ button) as `origin`: Copy git remote rm origin git remote rm upstream git remote add upstream https://github.com/Microsoft/TypeScript.git git remote add origin https://github.com/basarat/TypeScript.git Additionally I like to work off branches like `bas/` to have it show up cleaner in the branch listings. [](https://basarat.gitbook.io/typescript/overview/contributing#running-tests) Running Tests ------------------------------------------------------------------------------------------------ There are lots of `test` and `build` options in their JakeFile. You can run _all_ tests with `jake runtests` [](https://basarat.gitbook.io/typescript/overview/contributing#baselines) Baselines ---------------------------------------------------------------------------------------- Baselines are used to manage if there are any changes in the _expected_ output of the TypeScript compiler. Baselines are located in `tests/baselines`. * Reference (_expected_) baselines: `tests/baselines/reference` * Generated (_in this test run_) baselines : `tests/baselines/local` (this folder is in **.gitignore**) > If there are any differences between these folders tests will fail. You can diff the two folders with tools like BeyondCompare or KDiff3. If you think these changes in generated files are valid then accept baselines using `jake baseline-accept`. The changes to `reference` baselines will now show as a git diff you can commit. > Note that if you don't run _all_ tests then use `jake baseline-accept[soft]` which will only copy over the new files and not delete the whole `reference` directory. [](https://basarat.gitbook.io/typescript/overview/contributing#test-categories) Test Categories ---------------------------------------------------------------------------------------------------- There are different categories for different scenarios and even different test infrastructures. Here are a few of these explained. ### [](https://basarat.gitbook.io/typescript/overview/contributing#compiler-tests) Compiler Tests These ensure that compiling a file : * generates errors as expected * generated JS as expected * types are identified as expected * symbols are identified as expected These expectations are validated using the baselines infrastructure. #### [](https://basarat.gitbook.io/typescript/overview/contributing#creating-a-compiler-test) Creating a Compiler Test Test can be created by adding a new file `yourtest.ts` to `tests/cases/compiler`. As soon as you do so and run the tests you should get baseline failure. Accept these baselines (to get them to show up in git), and tweak them to be what you _expect_ them to be ... now get the tests to pass. Run all of these in isolation using `jake runtests tests=compiler`, or just your new file using `jake runtests tests=compiler/yourtest` I will even often do `jake runtests tests=compiler/yourtest || jake baseline-accept[soft]` and get the diff in `git`. [](https://basarat.gitbook.io/typescript/overview/contributing#debugging-tests) Debugging Tests ---------------------------------------------------------------------------------------------------- `jake runtests-browser tests=theNameOfYourTest` and debugging in-browser usually works pretty well. [](https://basarat.gitbook.io/typescript/overview/contributing#more) More ------------------------------------------------------------------------------ * An article by Remo : [https://dev.to/remojansen/learn-how-to-contribute-to-the-typescript-compiler-on-github-through-a-real-world-example-4df0](https://dev.to/remojansen/learn-how-to-contribute-to-the-typescript-compiler-on-github-through-a-real-world-example-4df0) ๐ŸŒน [PreviousEmitter SourceMaps](https://basarat.gitbook.io/typescript/overview/emitter/emitter-sourcemaps) Last updated 5 years ago * [Setup](https://basarat.gitbook.io/typescript/overview/contributing#setup) * [Setup Fork](https://basarat.gitbook.io/typescript/overview/contributing#setup-fork) * [Running Tests](https://basarat.gitbook.io/typescript/overview/contributing#running-tests) * [Baselines](https://basarat.gitbook.io/typescript/overview/contributing#baselines) * [Test Categories](https://basarat.gitbook.io/typescript/overview/contributing#test-categories) * [Compiler Tests](https://basarat.gitbook.io/typescript/overview/contributing#compiler-tests) * [Debugging Tests](https://basarat.gitbook.io/typescript/overview/contributing#debugging-tests) * [More](https://basarat.gitbook.io/typescript/overview/contributing#more) --- # Variables | TypeScript Deep Dive For example to tell TypeScript about the [`process` variable](https://nodejs.org/api/process.html) you _can_ do: Copy declare var process: any; > You don't _need_ to do this for `process` as there is already a [community maintained `node.d.ts`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/node/index.d.ts) > . This allows you to use the `process` variable without TypeScript complaining: Copy process.exit(); We recommend using an interface wherever possible e.g.: Copy interface Process { exit(code?: number): void; } declare var process: Process; This allows other people to _extend_ the nature of these global variables while still telling TypeScript about such modifications. E.g. consider the following case where we add an `exitWithLogging` function to process for our amusement: Copy interface Process { exitWithLogging(code?: number): void; } process.exitWithLogging = function() { console.log("exiting"); process.exit.apply(process, arguments); }; Let's look at interfaces in a bit more detail next. [PreviousDeclaration Files](https://basarat.gitbook.io/typescript/type-system/intro/d.ts) [NextInterfaces](https://basarat.gitbook.io/typescript/type-system/interfaces) Last updated 5 years ago --- # Binder Error Reporting | TypeScript Deep Dive Binding errors are added to the sourceFile's list of `bindDiagnostics`. An example error detected during binding is the use of `eval` or `arguments` as a variable name in `use strict` scenario. The relevant code is presented in its entirety below (`checkStrictModeEvalOrArguments` is called from multiple places, call stacks originating from `bindWorker` which calls different functions for different node `SyntaxKind`): Copy function checkStrictModeEvalOrArguments(contextNode: Node, name: Node) { if (name && name.kind === SyntaxKind.Identifier) { let identifier = name; if (isEvalOrArgumentsIdentifier(identifier)) { // We check first if the name is inside class declaration or class expression; if so give explicit message // otherwise report generic error message. let span = getErrorSpanForNode(file, name); file.bindDiagnostics.push(createFileDiagnostic(file, span.start, span.length, getStrictModeEvalOrArgumentsMessage(contextNode), identifier.text)); } } } function isEvalOrArgumentsIdentifier(node: Node): boolean { return node.kind === SyntaxKind.Identifier && ((node).text === "eval" || (node).text === "arguments"); } function getStrictModeEvalOrArgumentsMessage(node: Node) { // Provide specialized messages to help the user understand why we think they're in // strict mode. if (getContainingClass(node)) { return Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode; } if (file.externalModuleIndicator) { return Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode; } return Diagnostics.Invalid_use_of_0_in_strict_mode; } [PreviousBinder SymbolTable](https://basarat.gitbook.io/typescript/overview/binder/binder-symboltable) [NextChecker](https://basarat.gitbook.io/typescript/overview/checker) Last updated 5 years ago --- # Binder Declarations | TypeScript Deep Dive Linking between a `node` and a `symbol` is performed by a few functions. One function that is used to bind the `SourceFile` node to the source file Symbol (in case of an external module) is the `addDeclarationToSymbol` function Note : the `Symbol` for an external module source file is setup as `flags : SymbolFlags.ValueModule` and `name: '"' + removeFileExtension(file.fileName) + '"'`). Copy function addDeclarationToSymbol(symbol: Symbol, node: Declaration, symbolFlags: SymbolFlags) { symbol.flags |= symbolFlags; node.symbol = symbol; if (!symbol.declarations) { symbol.declarations = []; } symbol.declarations.push(node); if (symbolFlags & SymbolFlags.HasExports && !symbol.exports) { symbol.exports = {}; } if (symbolFlags & SymbolFlags.HasMembers && !symbol.members) { symbol.members = {}; } if (symbolFlags & SymbolFlags.Value && !symbol.valueDeclaration) { symbol.valueDeclaration = node; } } The important linking portions: * Creates a link to the Symbol from the AST node (`node.symbol`). * Adds the node as _one of_ the declarations of the Symbol (`symbol.declarations`). [](https://basarat.gitbook.io/typescript/overview/binder/binder-declarations#declaration) Declaration ---------------------------------------------------------------------------------------------------------- Declaration is just a `node` with an optional name. In `types.ts` [PreviousBinder Functions](https://basarat.gitbook.io/typescript/overview/binder/binder-functions) [NextBinder Container](https://basarat.gitbook.io/typescript/overview/binder/binder-container) Last updated 5 years ago Copy interface Declaration extends Node { _declarationBrand: any; name?: DeclarationName; } --- # Binder Functions | TypeScript Deep Dive Two critical binder functions are `bindSourceFile` and `mergeSymbolTable`. We will take a look at these next. [](https://basarat.gitbook.io/typescript/overview/binder/binder-functions#bindsourcefile) `bindSourceFile` --------------------------------------------------------------------------------------------------------------- Basically checks if `file.locals` is defined, if not it hands over to (a local function) `bind`. Note: `locals` is defined on `Node` and is of type `SymbolTable`. Note that `SourceFile` is also a `Node` (in fact a root node in the AST). TIP: local functions are used heavily within the TypeScript compiler. A local function very likely uses variables from the parent function (captured by closure). In the case of `bind` (a local function within `bindSourceFile`) it (or a function it calls) will setup the `symbolCount` and `classifiableNames` among others, that are then stored on the returned `SourceFile`. [](https://basarat.gitbook.io/typescript/overview/binder/binder-functions#bind) `bind` ------------------------------------------------------------------------------------------- Bind takes any `Node` (not just `SourceFile`). First thing it does is assign the `node.parent` (if `parent` variable has been setup ... which again is something the binder does during its processing within the `bindChildren` function), then hands off to `bindWorker` which does the _heavy_ lifting. Finally it calls `bindChildren` (a function that simply stores the binder state e.g. current `parent` within its function local vars, then calls `bind` on each child, and then restores the binder state). Now let's look at `bindWorker` which is the more interesting function. [](https://basarat.gitbook.io/typescript/overview/binder/binder-functions#bindworker) `bindWorker` ------------------------------------------------------------------------------------------------------- This function switches on `node.kind` (of type `SyntaxKind`) and delegates work to the appropriate `bindFoo` function (also defined within `binder.ts`). For example if the `node` is a `SourceFile` it calls (eventually and only if its an external file module) `bindAnonymousDeclaration` [](https://basarat.gitbook.io/typescript/overview/binder/binder-functions#bindfoo-functions) `bindFoo` functions --------------------------------------------------------------------------------------------------------------------- There are a few patterns common to `bindFoo` functions as well as some utility functions that these use. One function that is almost always used is the `createSymbol` function. It is presented in its entirety below: Copy function createSymbol(flags: SymbolFlags, name: string): Symbol { symbolCount++; return new Symbol(flags, name); } As you can see it is simply keeping the `symbolCount` (a local to `bindSourceFile`) up to date and creating the symbol with the specified parameters. [PreviousBinder](https://basarat.gitbook.io/typescript/overview/binder) [NextBinder Declarations](https://basarat.gitbook.io/typescript/overview/binder/binder-declarations) Last updated 5 years ago * [bindSourceFile](https://basarat.gitbook.io/typescript/overview/binder/binder-functions#bindsourcefile) * [bind](https://basarat.gitbook.io/typescript/overview/binder/binder-functions#bind) * [bindWorker](https://basarat.gitbook.io/typescript/overview/binder/binder-functions#bindworker) * [bindFoo functions](https://basarat.gitbook.io/typescript/overview/binder/binder-functions#bindfoo-functions) --- # Binder | TypeScript Deep Dive Most JavaScript transpilers out there are simpler than TypeScript because they provide little in the way of code analysis. The typical JavaScript transpilers only have the following flow: Copy SourceCode ~~Scanner~~> Tokens ~~Parser~~> AST ~~Emitter~~> JavaScript While the above architecture is true as a simplified understanding of TypeScript js generation, a key feature of TypeScript is its _Semantic_ system. In order to assist type checking (performed by the `checker`), the `binder` (in `binder.ts`) is used to connect the various parts of the source code into a coherent type system that can then be used by the `checker`. The main responsibility of the binder is to create _Symbols_. [](https://basarat.gitbook.io/typescript/overview/binder#symbol) Symbol ---------------------------------------------------------------------------- Symbols connect declaration nodes in the AST to other declarations contributing to the same entity. Symbols are the basic building blocks of the Semantic system. The symbol constructor is defined in `core.ts` (and `binder` actually uses the `objectAllocator.getSymbolConstructor` to get its hands on it). Here is the symbol constructor: Copy function Symbol(flags: SymbolFlags, name: string) { this.flags = flags; this.name = name; this.declarations = undefined; } `SymbolFlags` is a flag enum and is really used to identify additional classifications of the symbol (e.g. variable scope flags `FunctionScopedVariable` or `BlockScopedVariable` among others) [](https://basarat.gitbook.io/typescript/overview/binder#usage-by-checker) Usage by Checker ------------------------------------------------------------------------------------------------ The `binder` is actually used internally by the type `checker` which in turn is used by the `program`. The simplified call stack looks like: Copy program.getTypeChecker -> ts.createTypeChecker (in checker)-> initializeTypeChecker (in checker) -> for each SourceFile `ts.bindSourceFile` (in binder) // followed by for each SourceFile `ts.mergeSymbolTable` (in checker) The unit of work for the binder is a SourceFile. The `binder.ts` is driven by `checker.ts`. [PreviousParser Functions](https://basarat.gitbook.io/typescript/overview/parser/parser-functions) [NextBinder Functions](https://basarat.gitbook.io/typescript/overview/binder/binder-functions) Last updated 5 years ago * [Symbol](https://basarat.gitbook.io/typescript/overview/binder#symbol) * [Usage by Checker](https://basarat.gitbook.io/typescript/overview/binder#usage-by-checker) --- # Binder Container | TypeScript Deep Dive An AST node can be a container. This determines the kinds of `SymbolTables` the Node and associated Symbol will have. Container is an abstract concept (i.e. has no associated data structure). The concept is driven by a few things, one being the `ContainerFlags` enum. The function `getContainerFlags` (in `binder.ts`) drives this flag and is presented below: Copy function getContainerFlags(node: Node): ContainerFlags { switch (node.kind) { case SyntaxKind.ClassExpression: case SyntaxKind.ClassDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.EnumDeclaration: case SyntaxKind.TypeLiteral: case SyntaxKind.ObjectLiteralExpression: return ContainerFlags.IsContainer; case SyntaxKind.CallSignature: case SyntaxKind.ConstructSignature: case SyntaxKind.IndexSignature: case SyntaxKind.MethodDeclaration: case SyntaxKind.MethodSignature: case SyntaxKind.FunctionDeclaration: case SyntaxKind.Constructor: case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: case SyntaxKind.FunctionType: case SyntaxKind.ConstructorType: case SyntaxKind.FunctionExpression: case SyntaxKind.ArrowFunction: case SyntaxKind.ModuleDeclaration: case SyntaxKind.SourceFile: case SyntaxKind.TypeAliasDeclaration: return ContainerFlags.IsContainerWithLocals; case SyntaxKind.CatchClause: case SyntaxKind.ForStatement: case SyntaxKind.ForInStatement: case SyntaxKind.ForOfStatement: case SyntaxKind.CaseBlock: return ContainerFlags.IsBlockScopedContainer; case SyntaxKind.Block: // do not treat blocks directly inside a function as a block-scoped-container. // Locals that reside in this block should go to the function locals. Otherwise 'x' // would not appear to be a redeclaration of a block scoped local in the following // example: // // function foo() { // var x; // let x; // } // // If we placed 'var x' into the function locals and 'let x' into the locals of // the block, then there would be no collision. // // By not creating a new block-scoped-container here, we ensure that both 'var x' // and 'let x' go into the Function-container's locals, and we do get a collision // conflict. return isFunctionLike(node.parent) ? ContainerFlags.None : ContainerFlags.IsBlockScopedContainer; } return ContainerFlags.None; } It is _only_ invoked from the binder's `bindChildren` function which sets up a node as a `container` and/or a `blockScopedContainer` depending upon the evaluation of the `getContainerFlags` function. The function `bindChildren` is presented below: As you might recall from the section on binder functions : `bindChildren` is called from the `bind` function. So we have the recursive binding setup : `bind` calls `bindChildren` calls `bind` for each child. [PreviousBinder Declarations](https://basarat.gitbook.io/typescript/overview/binder/binder-declarations) [NextBinder SymbolTable](https://basarat.gitbook.io/typescript/overview/binder/binder-symboltable) Last updated 5 years ago Copy // All container nodes are kept on a linked list in declaration order. This list is used by // the getLocalNameOfContainer function in the type checker to validate that the local name // used for a container is unique. function bindChildren(node: Node) { // Before we recurse into a node's children, we first save the existing parent, container // and block-container. Then after we pop out of processing the children, we restore // these saved values. let saveParent = parent; let saveContainer = container; let savedBlockScopeContainer = blockScopeContainer; // This node will now be set as the parent of all of its children as we recurse into them. parent = node; // Depending on what kind of node this is, we may have to adjust the current container // and block-container. If the current node is a container, then it is automatically // considered the current block-container as well. Also, for containers that we know // may contain locals, we proactively initialize the .locals field. We do this because // it's highly likely that the .locals will be needed to place some child in (for example, // a parameter, or variable declaration). // // However, we do not proactively create the .locals for block-containers because it's // totally normal and common for block-containers to never actually have a block-scoped // variable in them. We don't want to end up allocating an object for every 'block' we // run into when most of them won't be necessary. // // Finally, if this is a block-container, then we clear out any existing .locals object // it may contain within it. This happens in incremental scenarios. Because we can be // reusing a node from a previous compilation, that node may have had 'locals' created // for it. We must clear this so we don't accidentally move any stale data forward from // a previous compilation. let containerFlags = getContainerFlags(node); if (containerFlags & ContainerFlags.IsContainer) { container = blockScopeContainer = node; if (containerFlags & ContainerFlags.HasLocals) { container.locals = {}; } addToContainerChain(container); } else if (containerFlags & ContainerFlags.IsBlockScopedContainer) { blockScopeContainer = node; blockScopeContainer.locals = undefined; } forEachChild(node, bind); container = saveContainer; parent = saveParent; blockScopeContainer = savedBlockScopeContainer; } --- # Binder SymbolTable | TypeScript Deep Dive SymbolTable is implemented as a simple HashMap. Here is the interface (`types.ts`): Copy interface SymbolTable { [index: string]: Symbol; } SymbolTables are initialized by binding. There are a few SymbolTables used by the compiler: On `Node`: Copy locals?: SymbolTable; // Locals associated with node On `Symbol`: Copy members?: SymbolTable; // Class, interface or literal instance members exports?: SymbolTable; // Module exports Note: We saw `locals` getting initialized (to `{}`) by `bindChildren` based on `ContainerFlags`. [](https://basarat.gitbook.io/typescript/overview/binder/binder-symboltable#symboltable-population) SymbolTable population ------------------------------------------------------------------------------------------------------------------------------- SymbolTables are populated with `Symbols` primarily by a call to `declareSymbol`. This function is presented below in entirety: Copy /** * Declares a Symbol for the node and adds it to symbols. Reports errors for conflicting identifier names. * @param symbolTable - The symbol table which node will be added to. * @param parent - node's parent declaration. * @param node - The declaration to be added to the symbol table * @param includes - The SymbolFlags that node has in addition to its declaration type (eg: export, ambient, etc.) * @param excludes - The flags which node cannot be declared alongside in a symbol table. Used to report forbidden declarations. */ function declareSymbol(symbolTable: SymbolTable, parent: Symbol, node: Declaration, includes: SymbolFlags, excludes: SymbolFlags): Symbol { Debug.assert(!hasDynamicName(node)); // The exported symbol for an export default function/class node is always named "default" let name = node.flags & NodeFlags.Default && parent ? "default" : getDeclarationName(node); let symbol: Symbol; if (name !== undefined) { // Check and see if the symbol table already has a symbol with this name. If not, // create a new symbol with this name and add it to the table. Note that we don't // give the new symbol any flags *yet*. This ensures that it will not conflict // with the 'excludes' flags we pass in. // // If we do get an existing symbol, see if it conflicts with the new symbol we're // creating. For example, a 'var' symbol and a 'class' symbol will conflict within // the same symbol table. If we have a conflict, report the issue on each // declaration we have for this symbol, and then create a new symbol for this // declaration. // // If we created a new symbol, either because we didn't have a symbol with this name // in the symbol table, or we conflicted with an existing symbol, then just add this // node as the sole declaration of the new symbol. // // Otherwise, we'll be merging into a compatible existing symbol (for example when // you have multiple 'vars' with the same name in the same container). In this case // just add this node into the declarations list of the symbol. symbol = hasProperty(symbolTable, name) ? symbolTable[name] : (symbolTable[name] = createSymbol(SymbolFlags.None, name)); if (name && (includes & SymbolFlags.Classifiable)) { classifiableNames[name] = name; } if (symbol.flags & excludes) { if (node.name) { node.name.parent = node; } // Report errors every position with duplicate declaration // Report errors on previous encountered declarations let message = symbol.flags & SymbolFlags.BlockScopedVariable ? Diagnostics.Cannot_redeclare_block_scoped_variable_0 : Diagnostics.Duplicate_identifier_0; forEach(symbol.declarations, declaration => { file.bindDiagnostics.push(createDiagnosticForNode(declaration.name || declaration, message, getDisplayName(declaration))); }); file.bindDiagnostics.push(createDiagnosticForNode(node.name || node, message, getDisplayName(node))); symbol = createSymbol(SymbolFlags.None, name); } } else { symbol = createSymbol(SymbolFlags.None, "__missing"); } addDeclarationToSymbol(symbol, node, includes); symbol.parent = parent; return symbol; } Which SymbolTable is populated is driven by the first argument to this function. e.g. when adding a declaration to a _container_ of kind `SyntaxKind.ClassDeclaration` or `SyntaxKind.ClassExpression` the function `declareClassMember` will get called which has the following code: [PreviousBinder Container](https://basarat.gitbook.io/typescript/overview/binder/binder-container) [NextBinder Error Reporting](https://basarat.gitbook.io/typescript/overview/binder/binder-diagnostics) Last updated 5 years ago Copy function declareClassMember(node: Declaration, symbolFlags: SymbolFlags, symbolExcludes: SymbolFlags) { return node.flags & NodeFlags.Static ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes) : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); } --- # static constructors | TypeScript Deep Dive TypeScript `class` (like JavaScript `class`) cannot have a static constructor. However, you can get the same effect quite easily by just calling it yourself: Copy class MyClass { static initialize() { // Initialization } } MyClass.initialize(); [PreviousJQuery tips](https://basarat.gitbook.io/typescript/main-1/jquery) [Nextsingleton pattern](https://basarat.gitbook.io/typescript/main-1/singleton) Last updated 5 years ago --- # Limit Property Setters | TypeScript Deep Dive Prefer explicit set/get functions (e.g. `setBar` and `getBar` functions) over setters/getters. Consider the following code: Copy foo.bar = { a: 123, b: 456 }; In the presence of setter/getters: Copy class Foo { a: number; b: number; set bar(value:{a:number,b:number}) { this.a = value.a; this.b = value.b; } } let foo = new Foo(); This is not a _good_ use of property setters. The person reading the first code sample has no context about all the things that will change. Whereas someone calling `foo.setBar(value)` might have an idea that something might change on `foo`. > Bonus points: Find references works better if you have different functions. In TypeScript tools if you find references for a getter or a setter you get _both_ whereas with explicit function calls you only get references to the relevant function. [PreviousAvoid Export Default](https://basarat.gitbook.io/typescript/main-1/defaultisbad) [NextoutFile caution](https://basarat.gitbook.io/typescript/main-1/outfile) Last updated 5 years ago --- # Build Toggles | TypeScript Deep Dive It is common to switch in JavaScript projects based on where they are being run. You can do this quite easily with webpack as it supports _dead code elimination_ based on environment variables. Add different targets in your `package.json` `scripts`: Copy "build:test": "webpack -p --config ./src/webpack.config.js", "build:prod": "webpack -p --define process.env.NODE_ENV='\"production\"' --config ./src/webpack.config.js", Of course I am assuming you have `npm install webpack --save-dev`. Now you can run `npm run build:test` etc. Using this variable is super easy as well: Copy /** * This interface makes sure we don't miss adding a property to both `prod` and `test` */ interface Config { someItem: string; } /** * We only export a single thing. The config. */ export let config: Config; /** * `process.env.NODE_ENV` definition is driven from webpack * * The whole `else` block will be removed in the emitted JavaScript * for a production build */ if (process.env.NODE_ENV === 'production') { config = { someItem: 'prod' } console.log('Running in prod'); } else { config = { someItem: 'test' } console.log('Running in test'); } > We use `process.env.NODE_ENV` just because it is conventional in a lot of JavaScript libraries themselves e.g. `React`. [PreviousFunction parameters](https://basarat.gitbook.io/typescript/main-1/functionparameters) [NextBarrel](https://basarat.gitbook.io/typescript/main-1/barrel) Last updated 5 years ago --- # Emitter Functions | TypeScript Deep Dive [](https://basarat.gitbook.io/typescript/overview/emitter/emitter-functions#emitfiles) `emitFiles` ------------------------------------------------------------------------------------------------------- Defined in `emitter.ts` here is the function signature: Copy // targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature export function emitFiles(resolver: EmitResolver, host: EmitHost, targetSourceFile?: SourceFile): EmitResult { `EmitHost` is just a simplified (as in narrowed down) version of `CompilerHost` (and is at runtime actually a `CompilerHost` for many use cases). The most interesting call stack from `emitFiles` is the following: Copy emitFiles -> emitFile(jsFilePath, targetSourceFile) -> emitJavaScript(jsFilePath, targetSourceFile); [](https://basarat.gitbook.io/typescript/overview/emitter/emitter-functions#emitjavascript) `emitJavaScript` ----------------------------------------------------------------------------------------------------------------- There is a lot of good comments in this function so we present it below : Copy function emitJavaScript(jsFilePath: string, root?: SourceFile) { let writer = createTextWriter(newLine); let write = writer.write; let writeTextOfNode = writer.writeTextOfNode; let writeLine = writer.writeLine; let increaseIndent = writer.increaseIndent; let decreaseIndent = writer.decreaseIndent; let currentSourceFile: SourceFile; // name of an exporter function if file is a System external module // System.register([...], function () {...}) // exporting in System modules looks like: // export var x; ... x = 1 // => // var x;... exporter("x", x = 1) let exportFunctionForFile: string; let generatedNameSet: Map = {}; let nodeToGeneratedName: string[] = []; let computedPropertyNamesToGeneratedNames: string[]; let extendsEmitted = false; let decorateEmitted = false; let paramEmitted = false; let awaiterEmitted = false; let tempFlags = 0; let tempVariables: Identifier[]; let tempParameters: Identifier[]; let externalImports: (ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration)[]; let exportSpecifiers: Map; let exportEquals: ExportAssignment; let hasExportStars: boolean; /** Write emitted output to disk */ let writeEmittedFiles = writeJavaScriptFile; let detachedCommentsInfo: { nodePos: number; detachedCommentEndPos: number }[]; let writeComment = writeCommentRange; /** Emit a node */ let emit = emitNodeWithoutSourceMap; /** Called just before starting emit of a node */ let emitStart = function (node: Node) { }; /** Called once the emit of the node is done */ let emitEnd = function (node: Node) { }; /** Emit the text for the given token that comes after startPos * This by default writes the text provided with the given tokenKind * but if optional emitFn callback is provided the text is emitted using the callback instead of default text * @param tokenKind the kind of the token to search and emit * @param startPos the position in the source to start searching for the token * @param emitFn if given will be invoked to emit the text instead of actual token emit */ let emitToken = emitTokenText; /** Called to before starting the lexical scopes as in function/class in the emitted code because of node * @param scopeDeclaration node that starts the lexical scope * @param scopeName Optional name of this scope instead of deducing one from the declaration node */ let scopeEmitStart = function(scopeDeclaration: Node, scopeName?: string) { }; /** Called after coming out of the scope */ let scopeEmitEnd = function() { }; /** Sourcemap data that will get encoded */ let sourceMapData: SourceMapData; if (compilerOptions.sourceMap || compilerOptions.inlineSourceMap) { initializeEmitterWithSourceMaps(); } if (root) { // Do not call emit directly. It does not set the currentSourceFile. emitSourceFile(root); } else { forEach(host.getSourceFiles(), sourceFile => { if (!isExternalModuleOrDeclarationFile(sourceFile)) { emitSourceFile(sourceFile); } }); } writeLine(); writeEmittedFiles(writer.getText(), /*writeByteOrderMark*/ compilerOptions.emitBOM); return; /// BUNCH OF LOCAL FUNCTIONS } Basically it sets up a bunch of locals (these functions form the _bulk_ of `emitter.ts`) and then hands off to a local function `emitSourceFile` which kicks off the emit. The `emitSourceFile` function just sets up the `currentSourceFile` and in turn hands off to a local `emit` function. The `emit` function handles _comment_ emit + _actual JavaScript_ emit. The _actual JavaScript_ emit is the job of `emitJavaScriptWorker` function. [](https://basarat.gitbook.io/typescript/overview/emitter/emitter-functions#emitjavascriptworker) `emitJavaScriptWorker` ----------------------------------------------------------------------------------------------------------------------------- The complete function: Recursion is done by simply calling other `emitFoo` function from these functions as needed e.g. from `emitFunctionDeclaration` : [PreviousEmitter](https://basarat.gitbook.io/typescript/overview/emitter) [NextEmitter SourceMaps](https://basarat.gitbook.io/typescript/overview/emitter/emitter-sourcemaps) Last updated 5 years ago * [emitFiles](https://basarat.gitbook.io/typescript/overview/emitter/emitter-functions#emitfiles) * [emitJavaScript](https://basarat.gitbook.io/typescript/overview/emitter/emitter-functions#emitjavascript) * [emitJavaScriptWorker](https://basarat.gitbook.io/typescript/overview/emitter/emitter-functions#emitjavascriptworker) Copy function emitSourceFile(sourceFile: SourceFile): void { currentSourceFile = sourceFile; exportFunctionForFile = undefined; emit(sourceFile); } Copy function emitJavaScriptWorker(node: Node) { // Check if the node can be emitted regardless of the ScriptTarget switch (node.kind) { case SyntaxKind.Identifier: return emitIdentifier(node); case SyntaxKind.Parameter: return emitParameter(node); case SyntaxKind.MethodDeclaration: case SyntaxKind.MethodSignature: return emitMethod(node); case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: return emitAccessor(node); case SyntaxKind.ThisKeyword: return emitThis(node); case SyntaxKind.SuperKeyword: return emitSuper(node); case SyntaxKind.NullKeyword: return write("null"); case SyntaxKind.TrueKeyword: return write("true"); case SyntaxKind.FalseKeyword: return write("false"); case SyntaxKind.NumericLiteral: case SyntaxKind.StringLiteral: case SyntaxKind.RegularExpressionLiteral: case SyntaxKind.NoSubstitutionTemplateLiteral: case SyntaxKind.TemplateHead: case SyntaxKind.TemplateMiddle: case SyntaxKind.TemplateTail: return emitLiteral(node); case SyntaxKind.TemplateExpression: return emitTemplateExpression(node); case SyntaxKind.TemplateSpan: return emitTemplateSpan(node); case SyntaxKind.JsxElement: case SyntaxKind.JsxSelfClosingElement: return emitJsxElement(node); case SyntaxKind.JsxText: return emitJsxText(node); case SyntaxKind.JsxExpression: return emitJsxExpression(node); case SyntaxKind.QualifiedName: return emitQualifiedName(node); case SyntaxKind.ObjectBindingPattern: return emitObjectBindingPattern(node); case SyntaxKind.ArrayBindingPattern: return emitArrayBindingPattern(node); case SyntaxKind.BindingElement: return emitBindingElement(node); case SyntaxKind.ArrayLiteralExpression: return emitArrayLiteral(node); case SyntaxKind.ObjectLiteralExpression: return emitObjectLiteral(node); case SyntaxKind.PropertyAssignment: return emitPropertyAssignment(node); case SyntaxKind.ShorthandPropertyAssignment: return emitShorthandPropertyAssignment(node); case SyntaxKind.ComputedPropertyName: return emitComputedPropertyName(node); case SyntaxKind.PropertyAccessExpression: return emitPropertyAccess(node); case SyntaxKind.ElementAccessExpression: return emitIndexedAccess(node); case SyntaxKind.CallExpression: return emitCallExpression(node); case SyntaxKind.NewExpression: return emitNewExpression(node); case SyntaxKind.TaggedTemplateExpression: return emitTaggedTemplateExpression(node); case SyntaxKind.TypeAssertionExpression: return emit((node).expression); case SyntaxKind.AsExpression: return emit((node).expression); case SyntaxKind.ParenthesizedExpression: return emitParenExpression(node); case SyntaxKind.FunctionDeclaration: case SyntaxKind.FunctionExpression: case SyntaxKind.ArrowFunction: return emitFunctionDeclaration(node); case SyntaxKind.DeleteExpression: return emitDeleteExpression(node); case SyntaxKind.TypeOfExpression: return emitTypeOfExpression(node); case SyntaxKind.VoidExpression: return emitVoidExpression(node); case SyntaxKind.AwaitExpression: return emitAwaitExpression(node); case SyntaxKind.PrefixUnaryExpression: return emitPrefixUnaryExpression(node); case SyntaxKind.PostfixUnaryExpression: return emitPostfixUnaryExpression(node); case SyntaxKind.BinaryExpression: return emitBinaryExpression(node); case SyntaxKind.ConditionalExpression: return emitConditionalExpression(node); case SyntaxKind.SpreadElementExpression: return emitSpreadElementExpression(node); case SyntaxKind.YieldExpression: return emitYieldExpression(node); case SyntaxKind.OmittedExpression: return; case SyntaxKind.Block: case SyntaxKind.ModuleBlock: return emitBlock(node); case SyntaxKind.VariableStatement: return emitVariableStatement(node); case SyntaxKind.EmptyStatement: return write(";"); case SyntaxKind.ExpressionStatement: return emitExpressionStatement(node); case SyntaxKind.IfStatement: return emitIfStatement(node); case SyntaxKind.DoStatement: return emitDoStatement(node); case SyntaxKind.WhileStatement: return emitWhileStatement(node); case SyntaxKind.ForStatement: return emitForStatement(node); case SyntaxKind.ForOfStatement: case SyntaxKind.ForInStatement: return emitForInOrForOfStatement(node); case SyntaxKind.ContinueStatement: case SyntaxKind.BreakStatement: return emitBreakOrContinueStatement(node); case SyntaxKind.ReturnStatement: return emitReturnStatement(node); case SyntaxKind.WithStatement: return emitWithStatement(node); case SyntaxKind.SwitchStatement: return emitSwitchStatement(node); case SyntaxKind.CaseClause: case SyntaxKind.DefaultClause: return emitCaseOrDefaultClause(node); case SyntaxKind.LabeledStatement: return emitLabelledStatement(node); case SyntaxKind.ThrowStatement: return emitThrowStatement(node); case SyntaxKind.TryStatement: return emitTryStatement(node); case SyntaxKind.CatchClause: return emitCatchClause(node); case SyntaxKind.DebuggerStatement: return emitDebuggerStatement(node); case SyntaxKind.VariableDeclaration: return emitVariableDeclaration(node); case SyntaxKind.ClassExpression: return emitClassExpression(node); case SyntaxKind.ClassDeclaration: return emitClassDeclaration(node); case SyntaxKind.InterfaceDeclaration: return emitInterfaceDeclaration(node); case SyntaxKind.EnumDeclaration: return emitEnumDeclaration(node); case SyntaxKind.EnumMember: return emitEnumMember(node); case SyntaxKind.ModuleDeclaration: return emitModuleDeclaration(node); case SyntaxKind.ImportDeclaration: return emitImportDeclaration(node); case SyntaxKind.ImportEqualsDeclaration: return emitImportEqualsDeclaration(node); case SyntaxKind.ExportDeclaration: return emitExportDeclaration(node); case SyntaxKind.ExportAssignment: return emitExportAssignment(node); case SyntaxKind.SourceFile: return emitSourceFileNode(node); } } Copy function emitFunctionDeclaration(node: FunctionLikeDeclaration) { if (nodeIsMissing(node.body)) { return emitOnlyPinnedOrTripleSlashComments(node); } if (node.kind !== SyntaxKind.MethodDeclaration && node.kind !== SyntaxKind.MethodSignature) { // Methods will emit the comments as part of emitting method declaration emitLeadingComments(node); } // For targeting below es6, emit functions-like declaration including arrow function using function keyword. // When targeting ES6, emit arrow function natively in ES6 by omitting function keyword and using fat arrow instead if (!shouldEmitAsArrowFunction(node)) { if (isES6ExportedDeclaration(node)) { write("export "); if (node.flags & NodeFlags.Default) { write("default "); } } write("function"); if (languageVersion >= ScriptTarget.ES6 && node.asteriskToken) { write("*"); } write(" "); } if (shouldEmitFunctionName(node)) { emitDeclarationName(node); } emitSignatureAndBody(node); if (languageVersion < ScriptTarget.ES6 && node.kind === SyntaxKind.FunctionDeclaration && node.parent === currentSourceFile && node.name) { emitExportMemberAssignments((node).name); } if (node.kind !== SyntaxKind.MethodDeclaration && node.kind !== SyntaxKind.MethodSignature) { emitTrailingComments(node); } } --- # outFile caution | TypeScript Deep Dive Its a bad idea for you to use because of the following reasons: * Runtime Errors * Fast compile * Global scope * Hard to analyze * Hard to scale * `_references` * Code reuse * Multiple Targets * Isolated Compile [](https://basarat.gitbook.io/typescript/main-1/outfile#runtime-errors) Runtime Errors ------------------------------------------------------------------------------------------- If your code depends on any form of js ordering you will get random errors at runtime. * **class inheritance can break at runtime.** Consider `foo.ts`: Copy class Foo { } and a `bar.ts`: If you fail to compile it in correct order e.g. perhaps alphabetically `tsc bar.ts foo.ts` the code will compile fine but error at runtime with `ReferenceError`. * **module splitting can fail at runtime.** Consider `foo.ts`: And `bar.ts`: If you fail to compile it in correct order e.g. perhaps alphabetically `tsc bar.ts foo.ts` the code will compile fine but _silently_ fail at runtime with `bar` set to `NaN`. [](https://basarat.gitbook.io/typescript/main-1/outfile#fast-compile) Fast compile --------------------------------------------------------------------------------------- If you use `--out` then single `.ts` files cannot be codegened into single `.js` files in isolation without unnecessary hacks. `--out` essentially forces a slower incremental build. Also source maps are positionally sensitive and run-length encoded so most of the map has to be rebuilt on a recompile if you use source maps (which you should!). At high-10s to 100s kloc combined itโ€™s going to get slow. [](https://basarat.gitbook.io/typescript/main-1/outfile#global-scope) Global Scope --------------------------------------------------------------------------------------- Sure you can use name spaces but its still on `window` if you run it in the browser. Namespaces are just an unnecessary workaround. Also `///