The Concise TypeScript Book
The Concise TypeScript Book provides a comprehensive and succinct overview of TypeScript's capabilities. It offers clear explanations covering all aspects found in the latest version of the language, from its powerful type system to advanced features. Whether you're a beginner or an experienced developer, this book is an invaluable resource to enhance your understanding and proficiency in TypeScript.
This book is completely Free and Open Source.
If you found this TypeScript book valuable and wish to contribute, consider supporting my efforts via PayPal. Thanks!
Translations
This book has been translated into several language versions, including:
Downloads and website
You can also download the Epub version:
https://github.com/gibbok/typescript-book/tree/main/downloads
An online version is available at:
https://gibbok.github.io/typescript-book
Table of Contents
- The Concise TypeScript Book
- Translations
- Downloads and website
- Table of Contents
- Introduction
- About the Author
- TypeScript Introduction
- Getting Started With TypeScript
- Exploring the Type System
- The TypeScript Language Service
- Structural Typing
- TypeScript Fundamental Comparison Rules
- Types as Sets
- Assign a type: Type Declarations and Type Assertions
- Property Checking and Excess Property Checking
- Weak Types
- Strict Object Literal Checking (Freshness)
- Type Inference
- More Advanced Inferences
- Type Widening
- Const
- Explicit Type Annotation
- Type Narrowing
- Primitive Types
- Type Annotations
- Optional Properties
- Readonly Properties
- Index Signatures
- Extending Types
- Literal Types
- Literal Inference
- strictNullChecks
- Enums
- Narrowing
- Assignments
- Control Flow Analysis
- Type Predicates
- Discriminated Unions
- The never Type
- Exhaustiveness checking
- Object Types
- Tuple Type (Anonymous)
- Named Tuple Type (Labeled)
- Fixed Length Tuple
- Union Type
- Intersection Types
- Type Indexing
- Type from Value
- Type from Func Return
- Type from Module
- Mapped Types
- Mapped Type Modifiers
- Conditional Types
- Distributive Conditional Types
- infer Type Inference in Conditional Types
- Predefined Conditional Types
- Template Union Types
- Any type
- Unknown type
- Void type
- Never type
- Interface and Type
- Built-in Type Primitives
- Common Built-in JS Objects
- Overloads
- Merging and Extension
- Differences between Type and Interface
- Class
- Generics
- Erased Structural Types
- Namespacing
- Symbols
- Triple-Slash Directives
- Type Manipulation
- Creating Types from Types
- Indexed Access Types
- Utility Types
- Awaited<T>
- Partial<T>
- Required<T>
- Readonly<T>
- Record<K, T>
- Pick<T, K>
- Omit<T, K>
- Exclude<T, U>
- Extract<T, U>
- NonNullable<T>
- Parameters<T>
- ConstructorParameters<T>
- ReturnType<T>
- InstanceType<T>
- ThisParameterType<T>
- OmitThisParameter<T>
- ThisType<T>
- Uppercase<T>
- Lowercase<T>
- Capitalize<T>
- Uncapitalize<T>
- NoInfer<T>
- Others
- Errors and Exception Handling
- Mixin classes
- Asynchronous Language Features
- Iterators and Generators
- TsDocs JSDoc Reference
- @types
- JSX
- ES6 Modules
- ES7 Exponentiation Operator
- The for-await-of Statement
- New target meta-property
- Dynamic Import Expressions
- "tsc –watch"
- Non-null Assertion Operator
- Defaulted declarations
- Optional Chaining
- Nullish coalescing operator
- Template Literal Types
- Function overloading
- Recursive Types
- Recursive Conditional Types
- ECMAScript Module Support in Node
- Assertion Functions
- Variadic Tuple Types
- Boxed types
- Covariance and Contravariance in TypeScript
- Template String Pattern Index Signatures
- The satisfies Operator
- Type-Only Imports and Export
- using declaration and Explicit Resource Management
- Import Attributes
Introduction
Welcome to The Concise TypeScript Book! This guide equips you with essential knowledge and practical skills for effective TypeScript development. Discover key concepts and techniques to write clean, robust code. Whether you're a beginner or an experienced developer, this book serves as both a comprehensive guide and a handy reference for leveraging TypeScript's power in your projects.
This book covers TypeScript 5.2.
About the Author
Simone Poggiali is an experienced Senior Front-end Developer with a passion for writing professional-grade code since the 90s. Throughout his international career, he has contributed to numerous projects for a wide range of clients, from startups to large organizations. Notable companies such as HelloFresh, Siemens, O2, and Leroy Merlin have benefited from his expertise and dedication.
You can reach Simone Poggiali on the following platforms:
- LinkedIn: https://www.linkedin.com/in/simone-poggiali
- GitHub: https://github.com/gibbok
- Twitter: https://twitter.com/gibbok_coding
- Email: gibbok.coding📧gmail.com
TypeScript Introduction
What is TypeScript?
TypeScript is a strongly typed programming language that builds on JavaScript. It was originally designed by Anders Hejlsberg in 2012 and is currently developed and maintained by Microsoft as an open source project.
TypeScript compiles to JavaScript and can be executed in any JavaScript runtime (e.g., a browser or server Node.js).
TypeScript supports multiple programming paradigms such as functional, generic, imperative, and object-oriented. TypeScript is neither an interpreted nor a compiled language.
Why TypeScript?
TypeScript is a strongly typed language that helps prevent common programming mistakes and avoid certain kinds of run-time errors before the program is executed.
A strongly typed language allows the developer to specify various program constraints and behaviors in the data type definitions, facilitating the ability to verify the correctness of the software and prevent defects. This is especially valuable in large-scale applications.
Some of the benefits of TypeScript:
- Static typing, optionally strongly typed
- Type Inference
- Access to ES6 and ES7 features
- Cross-Platform and Cross-browser Compatibility
- Tooling support with IntelliSense
TypeScript and JavaScript
TypeScript is written in .ts
or .tsx
files, while JavaScript files are written in .js
or .jsx
.
Files with the extension .tsx
or .jsx
can contain JavaScript Syntax Extension JSX, which is used in React for UI development.
TypeScript is a typed superset of JavaScript (ECMAScript 2015) in terms of syntax. All JavaScript code is valid TypeScript code, but the reverse is not always true.
For instance, consider a function in a JavaScript file with the .js
extension, such as the following:
const sum = (a, b) => a + b;
The function can be converted and used in TypeScript by changing the file extension to .ts
. However, if the same function is annotated with TypeScript types, it cannot be executed in any JavaScript runtime without compilation. The following TypeScript code will produce a syntax error if it is not compiled:
const sum = (a: number, b: number): number => a + b;
TypeScript was designed to detect possible exceptions that can occur at runtime during compilation time by having the developer define the intent with type annotations. In addition, TypeScript can also catch issues if no type annotation is provided. For instance, the following code snippet does not specify any TypeScript types:
const items = [{ x: 1 }, { x: 2 }];
const result = items.filter(item => item.y);
In this case, TypeScript detects an error and reports:
Property 'y' does not exist on type '{ x: number; }'.
TypeScript's type system is largely influenced by the runtime behavior of JavaScript. For example, the addition operator (+), which in JavaScript can either perform string concatenation or numeric addition, is modeled in the same way in TypeScript:
const result = '1' + 1; // Result is of type string
The team behind TypeScript has made a deliberate decision to flag unusual usage of JavaScript as errors. For instance, consider the following valid JavaScript code:
const result = 1 + true; // In JavaScript, the result is equal 2
However, TypeScript throws an error:
Operator '+' cannot be applied to types