Typesafe(ish) React
RJ Zaworski
director of growth, koan.co · @rjzaworski · github.com/rjz
Slide 2
Slide 2 text
“
Types
...tell the
compiler or
interpreter how
the programmer
intends to use
the data”
(https://en.wikipedia.org/wiki/Data_type, http://bit.ly/2C09A0w)
Slide 3
Slide 3 text
“
Type safety
...the extent to which a programming language
discourages or prevents type errors”
> const sayHello = "I'm a string.";
> sayHello();
TypeError: sayHello is not a function
(https://en.wikipedia.org/wiki/Type_safety)
Slide 4
Slide 4 text
Type checks
★ Static v. dynamic
(when is check made?)
★ Strong v. weak
(how strict is it?) Dynamic Static
Weak JavaScript C (sort of)
Strong Python, Ruby
Flow, Reason,
TypeScript
Slide 5
Slide 5 text
JavaScript is everywhere.
Slide 6
Slide 6 text
JavaScript is everywhere.
Slide 7
Slide 7 text
When it breaks
Read & parse
Static checks Linting
Compile Formatting
Test?
Run Type checking
Hello, world!
Even good programmers
do bad things...
$ tsc point.ts
point.ts:8:3 - error TS2339:
Property 'z' does not exist on
type 'Point'.
8 p.z = 42;
~
type Point = {
x: number,
y: number,
};
const p: Point = { x: 1, y: 1 };
p.z = 42;
point.ts
Slide 15
Slide 15 text
Interfaces
★ Define data shape
★ Extensible
interface Bounds {
readonly w: number, // width
readonly h: number, // height
area(): number,
}
function square (a: number) {
return {
h: a,
w: a,
area: () => a * a,
};
}
function perimeter (b: Bounds) {
return 2 * (b.w + b.h);
}
interface.ts
h
w
area()
Slide 16
Slide 16 text
Generics
★ Reusable
★ Type-independent
type Circle = Bounds & {
readonly r: number,
}
function circle (r: number) {
const area = () => Math.PI * r * r;
return { r, h: r + r, w: r + r, area };
}
const mapper = (f: (t: T) => U) =>
(ts: T[]) => ts.map(f);
const circleMapper =
mapper(circle);
const circles = circleMapper([1, 2, 3]);
generics.ts
h
w
r
Slide 17
Slide 17 text
React
Slide 18
Slide 18 text
Getting started
1. Scaffold
$ npx create-react-app myapp \
--scripts-version=react-scripts-ts
2. Install some dependencies
$ npm i redux
$ npm i react-redux
3. And some @types
$ npm i @types/react-redux
Slide 19
Slide 19 text
Yet another todo list™
(http://tspirates.surge.sh/; https://github.com/rjz/tspirates)