Introduction to the TypeScript Language
- JavaScript is great because of its reach
- JavaScript is everywhere
- JavaScript is great because of available libraries
- For server and client
- JavaScript (sometimes) sucks because of missing types
- Limited editor support (IntelliSense, refactoring)
- Runtime errors instead of compile-time errors
Our wish: Productivity of robustness of typed languages like C# or Java with reach of JavaScript
- Superset of JavaScript
- Valid JavaScript is (mostly) valid TypeScript
- TypeScript defines add-ons to ECMAScript (primarily type information)
- Existing JavaScript code works perfectly with TypeScript
- TypeScript compiles into JavaScript
- Use it where you can use JavaScript
- Compile-time error checking base on type information
- Generated code follows usual JavaScript patterns (e.g. pseudo-classes)
- Built-in transpiler similar to babel
- Great tool support
- e.g. Visual Studio Code
- Install locally:
npm install typescript --save-dev- Run compiler
tscfrom NPM script - Run compiler from
node_modules:./node_modules/.bin/tsc
- Run compiler
- Install globally:
npm install --global typescript- Run compiler from every folder with
tsc
- Run compiler from every folder with
- Install TypeScript with development tools
- Tip: Consider ts-node to execute TypeScript files directly without compiling
let n: number; // typed variable
let a; // no type -> any
const s = "Max"; // contextual typing -> string
n = 5; // valid because 5 is a number
a = 5; // valid because a is of type any
a = "Hello"; // valid because a is of type any
n = "Hello"; // compile time error because "Hello" is not a number
- Try it in TypeScript Playground
- Try code navigation (right-click)
- Try IntelliSense
- Types are used during editing and compiling
- No type information in resulting JavaScript code
- Contextual Typing: Determine result type from expressions automatically
- Copy the following code into TypeScript Playground
- Watch the transpiler work
- Try IntelliSense
class Person {
get firstName(): string { return "Tom"; }
async doSomethingAsync(): Promise<number> {
const result: number = await Promise.resolve(42);
return result;
}
doSometing(callback: (result: number) => void) { callback(42); }
}
const p = new Person();
p.doSometing(result => console.log(result));
- TypeScript Handbook: Basic Types
- Important basic types:
boolean,number,string,array,tupleenum= enumerationsany= type not known at compile timevoid= no type at all
- Type assertions
- Advanced topics (not in scope for exams):
never
Important rule: Forget
var, always useconstorlet
<!--#include file="typescript-fundamentals/0010-Basic-Types/bool-number-string.ts" -->
<!--#include file="typescript-fundamentals/0010-Basic-Types/any-array.ts" -->
<!--#include file="typescript-fundamentals/0010-Basic-Types/tuple-enum.ts" -->
Note problems of var --> avoid it!
<!--#include file="typescript-fundamentals/0010-Basic-Types/var.ts" -->
<!--#include file="typescript-fundamentals/0010-Basic-Types/let.ts" -->
<!--#include file="typescript-fundamentals/0020-Objects-and-Functions/objects.ts" -->
- TypeScript Handbook: Functions
functionkeyword vs. arrow functions- Type inferrence
- Parameters (required, optional, default parameters)
- Advanced topics (not in scope for exams):
- Rest parameters, details of
this, overloads
- Rest parameters, details of
<!--#include file="typescript-fundamentals/0020-Objects-and-Functions/functions.ts" -->
- TypeScript Handbook: Interfaces
- Works differently compared to many other languages like C#
- "Duck Typing" aka Structural Subtyping
- Interfaces can extend each other
- Advanced topics (not in scope for exams):
- Function types, indexable types, class types, hybrid types
<!--#include file="typescript-fundamentals/0030-Interfaces-and-Classes/interface.ts" -->
<!--#include file="typescript-fundamentals/0030-Interfaces-and-Classes/class-with-interface.ts" -->
<!--#include file="typescript-fundamentals/0030-Interfaces-and-Classes/duck-typing.ts" -->
- TypeScript Handbook: Classes
- Constructors
- Accessibility of members:
public,private,protected - Static members vs. instance members
- Inheritance
- Abstract classes
readonlyproperties- Accessors
- TypeScript Handbook: Generics
- Generic functions
- Generic classes
- Generic interfaces
- Advanced topics (not in scope for exams):
- Generic Constraints
<!--#include file="typescript-fundamentals/0030-Interfaces-and-Classes/generics.ts" -->
- TypeScript Handbook: Iterators and Generators
for..of= iterate over iterable object (e.g. array)for..in= iterate over all keys of an object (see also Object.keys())
- TypeScript Handbook: Modules
- Conceptually similar to ECMAScript modules
export/import- Ambient modules
@typeson NPM
- Advanced topics (not in scope for exams):
- Code generation for modules, optional module loading
module.ts
<!--#include file="typescript-fundamentals/0050-Modules/module.ts" -->
anotherModule.ts
<!--#include file="typescript-fundamentals/0050-Modules/anotherModule.ts" -->
<!--#include file="typescript-fundamentals/0050-Modules/app.ts" -->
Exercise: Try this sample with different module systems (e.g. --module commonjs)
- TypeScript Handbook: Declaration Files - Consumption
- Many libraries are written in JavaScript, not TypeScript
- Black box for TypeScript compiler
- External declarations for globals (e.g.
$in jQuery), interfaces, etc. necessary - TypeScript declaration files (
.d.ts)- Similar to C++ header files
npm install @types/...(e.g.npm install @types/chalkforchalk)
- TypeScript Handbook: tsconfig.json
- Compiler has a large number of compiler options
- Options can be passed...
- ...on the command line (
tsc --help) - ...in
tsconfig.json(preferred)
- ...on the command line (
- Tip: Generate basic
tsconfig.jsonfile withtsc --init
- lib: List of library files to be included in the compilation
(e.g. ES2015, DOM) - module: Specify module code generation (e.g. CommonJS, AMD, UMD;
see also What Is AMD, CommonJS, and UMD?) - moduleResolution: Rule of thumb: Set it to Node if you include packages from NPM
- outFile, outDir: File and directory ouput structure
- sourceMap: Generate source map files for debugging
- target: ECMAScript target version (e.g. ES2015, ES2016)
- --watch: Run the compiler in watch mode: Watch input files and trigger recompilation on changes.
- --version: Print the compiler's version
- Not in scope for exams
- Symbols
- Namespaces
- JSX
- Decorators
- Mixins
- TypeScript offers you the reach of JavaScript
- TypeScript makes you more productive (e.g. IntelliSense)
- Ready for larger projects and larger teams
- TypeScript produces less runtime errors
- Because of compile-time type checking
- Exercises