Type-checking
with examples in TypeScript
Dapeng Li
Agenda
-
Type-checking
-
Custom types with TS
-
Some of TS' caveats
-
Summary
TypeScript
Reports type errors
JavaScript
Doesn't JavaScript have types?
And report type errors?
TS compilation
Type system *
-
Dynamic
- type-checking at runtime
-
Static
- type-checking at compile time
Source-to-source compile = transcompile = transpile **
Samurai
Ninja
OO Constructs
Class = state + behaviour
Inheritance
Inheritance
Inheritance
-
models is-a relationship
-
a strong form of coupling
-
single inheritance
Interface: contract
Interface
-
Models can-do relationships
-
contract w/o impl.
-
weaker coupling than class
-
class can impl. 1+ interfaces
Mixin: contract + impl.
Mixin in TypeScript: step 1/2
Mixin (cont.)
Mixin in TypeScript: step 2/2
Mixin
-
interface w/ impl.
-
best of both worlds?
-
be ware of the coupling
Generics
operation doesn't care about type
Generics
preserving type
Generic constraints
Caveats & "False Friends"
-
Type-checking rules
-
Variance
Compatible types?
// This is TypeScript
class Cat { name: string; run() {console.log("cat runs");} }
class Dog { name: string; run() {console.log("dog runs");} }
let cat: Cat = new Cat(); // fine
let dog: Dog = new Dog(); // fine
dog = cat; // what about this?
Type compatibility *
-
Structural
- check structures
-
Nominal
- check names/declarations
Structural TS
Structural TS
-
Structural on public members
-
Nominal on private/protected members *
Java: too strict for Catdog
Variance *
-
Dog[] and Animal[]
-
(Dog -> void) and (Animal -> void)
Dog is compatible with Animal
Variance *
-
Covariant
-
Contravariant
-
Invariant
-
Bivariant **
let animal: Animal = new Dog();
let animals: Animal[] = [new Dog()];
let dogs: dog[] = [new Animal()];
let animals: Animal[] = [new Dog()];
let dogs: dog[] = [new Animal()];
// no code here...
Variance in TS
TypeScript is helpful
Tooling support
TypeScript is helpful
Think with constraints
-
Be more precise
-
Keep things separated
TypeScript is helpful
Stepping stone to OO work
Community is growing
TypeScript is young
-
Lacks guidance
-
Can be confusing
Personal suggestions
-
Learn and use it
-
Be selective
-
Take it slowly
Takeaway
-
Dynamic vs. Static type-checking
-
Structural vs. Nominal typing
-
Class, Interface, Mixin and Generics
Questions?
class-based languages
*
* Classes, Interfaces, Mixins & Generics
Type-checking with examples in TypeScript
By Dapeng Li
Type-checking with examples in TypeScript
- 622