# Typing in JS
### Greg Hurrell
### [@wincent](https://github.com/wincent/)
Quiz π
[1, NaN, 'foo'] + {a: true}
ππΌ '1,NaN,foo[object Object]'
10 / new Date()
ππΌ 6.454428654138961e-12
Math.min('10', [3])
ππΌ 3
true * false
ππΌ 0
My background
Or, why this is going to be a totally unbiased presentation
- Sat next to the Flow team at Facebook.
- Early adopter (2014) of Flow prior to open source release.
- Worked on frameworks and very large apps with complex typing requirements (in Flow).
- 5 years working with Flow.
- 5 days working with TypeScript.
# Me using Flow.
# The Flow team.
Yes
# Vanilla JS π
* Dynamic.
* Runs almost everywhere.
* Turing complete!
* Empires have been built on JavaScript...
* ...but it can be hard to do really big, robust things with it.
# TypeScript π₯
* Modern JS designed with speed, productivity and safety in mind.
* A big upgrade from untyped JavaScript.
# Flow π§
* Deadly serious type system for large codebases.
* A big upgrade from untyped JavaScript.
# Type systems overview
Type annotations
function increment(x: number): number {
return x + 1;
}
increment(1); // OK
increment(null); // Cannot call `increment` with `null`
Implicit return types
function increment(x: number) {
return x + 1;
}
increment(1); // OK
increment(null); // Cannot call `increment` with `null`
Catching implementation errors
function increment(x: number): string {
return x + 1;
}
// Cannot return `x + 1` because
// number is incompatible with string
Compiler output
function increment(x) {
return x + 1;
}
increment(1);
increment(null);
function process(input: Array<π©>): Array<π©> {
return input.map(eatDonut);
}
type Fruit = π | π | π;
function eat(fruit: Fruit) {
// Eat the fruit...
}
function runEventLoop(): never {
while (true) {
processInput();
updateGameState();
renderFrame();
}
}
class FastFood<T: π | π> {
_food: T;
constructor(food: T) {
this._food = food;
}
serve(): T {
return this._food;
}
}
function nullthrows<T>(value: T): NonNullable<T> {
if (value == null) {
throw new Error('Unexpected null-ish value');
}
return value as NonNullable<T>;
}
function isObject(value: unknown): value is object {
return (
value !== null &&
Object.prototype.toString.call(value) === '[object Object]'
);
}
# Resources for haters... π
* [The TypeScript Tax](https://medium.com/javascript-scene/the-typescript-tax-132ff4cb175b)
* [You Might Not Need TypeScript (or Static Types)](https://medium.com/javascript-scene/you-might-not-need-typescript-or-static-types-aa7cb670a77b)
* [The ever-lasting strife of static vs dynamic typing β TypeScript won't help](https://habr.com/en/post/437844/)
* [Why do people hate typescript?](https://www.quora.com/Why-do-people-hate-typescript) (Quora)