Skip to content

Latest commit

 

History

History
350 lines (249 loc) · 10.2 KB

File metadata and controls

350 lines (249 loc) · 10.2 KB

TypeScript Fundamentals

Introduction to the TypeScript Language

Why TypeScript?

  • 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

What is TypeScript?

  • 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

Install TypeScript

  • Install locally: npm install typescript --save-dev
    • Run compiler tsc from NPM script
    • Run compiler from node_modules: ./node_modules/.bin/tsc
  • Install globally: npm install --global typescript
    • Run compiler from every folder with tsc
  • Install TypeScript with development tools
  • Tip: Consider ts-node to execute TypeScript files directly without compiling

Type Fundamentals

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

Type Fundamentals (cont.)

  • 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));

Basic Types

  • TypeScript Handbook: Basic Types
  • Important basic types:
    • boolean, number, string, array, tuple
    • enum = enumerations
    • any = type not known at compile time
    • void = no type at all
  • Type assertions
  • Advanced topics (not in scope for exams):
    • never

Important rule: Forget var, always use const or let

Basic Types (cont.)

<!--#include file="typescript-fundamentals/0010-Basic-Types/bool-number-string.ts" -->

Basic Types (cont.)

<!--#include file="typescript-fundamentals/0010-Basic-Types/any-array.ts" -->

Basic Types (cont.)

<!--#include file="typescript-fundamentals/0010-Basic-Types/tuple-enum.ts" -->

Basic Types (cont.)

Note problems of var --> avoid it!

<!--#include file="typescript-fundamentals/0010-Basic-Types/var.ts" -->

Basic Types (cont.)

<!--#include file="typescript-fundamentals/0010-Basic-Types/let.ts" -->

Objects

<!--#include file="typescript-fundamentals/0020-Objects-and-Functions/objects.ts" -->

Functions

  • TypeScript Handbook: Functions
  • function keyword vs. arrow functions
  • Type inferrence
  • Parameters (required, optional, default parameters)
  • Advanced topics (not in scope for exams):
    • Rest parameters, details of this, overloads

Functions (cont.)

<!--#include file="typescript-fundamentals/0020-Objects-and-Functions/functions.ts" -->

Interfaces

  • 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

Interfaces (cont.)

<!--#include file="typescript-fundamentals/0030-Interfaces-and-Classes/interface.ts" -->

Interfaces (cont.)

<!--#include file="typescript-fundamentals/0030-Interfaces-and-Classes/class-with-interface.ts" -->

Duck Typing (cont.)

<!--#include file="typescript-fundamentals/0030-Interfaces-and-Classes/duck-typing.ts" -->

Classes

  • TypeScript Handbook: Classes
  • Constructors
  • Accessibility of members: public, private, protected
  • Static members vs. instance members
  • Inheritance
  • Abstract classes
  • readonly properties
  • Accessors

Generics

  • TypeScript Handbook: Generics
  • Generic functions
  • Generic classes
  • Generic interfaces
  • Advanced topics (not in scope for exams):
    • Generic Constraints

Generics (cont.)

<!--#include file="typescript-fundamentals/0030-Interfaces-and-Classes/generics.ts" -->

for..of and for..in

Modules

  • TypeScript Handbook: Modules
  • Conceptually similar to ECMAScript modules
  • export/import
  • Ambient modules
  • Advanced topics (not in scope for exams):
    • Code generation for modules, optional module loading

Modules (cont.)

module.ts

<!--#include file="typescript-fundamentals/0050-Modules/module.ts" -->

anotherModule.ts

<!--#include file="typescript-fundamentals/0050-Modules/anotherModule.ts" -->

Modules (cont.)

<!--#include file="typescript-fundamentals/0050-Modules/app.ts" -->

Exercise: Try this sample with different module systems (e.g. --module commonjs)

Declaration Files

  • 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/chalk for chalk)

Project Configuration

  • 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)
  • Tip: Generate basic tsconfig.json file with tsc --init

Important Compiler Options

  • 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

Advanced Topics

  • Not in scope for exams
  • Symbols
  • Namespaces
  • JSX
  • Decorators
  • Mixins

Summary: TypeScript Goals

  • 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

Further Readings and Exercises