-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
1561 lines (1458 loc) · 81.1 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>reveal.js</title>
<link rel="stylesheet" href="css/reset.css">
<link rel="stylesheet" href="css/reveal.css">
<link rel="stylesheet" href="css/theme/black.css">
<!-- Theme used for syntax highlighting of code -->
<link rel="stylesheet" href="lib/css/monokai.css">
<!-- Printing and PDF exports -->
<script>
var link = document.createElement( 'link' );
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = window.location.search.match( /print-pdf/gi ) ? 'css/print/pdf.css' : 'css/print/paper.css';
document.getElementsByTagName( 'head' )[0].appendChild( link );
</script>
<style>
.h-layout {
display: flex;
height: 600px;
}
.h-layout > * {
flex-grow: 1;
}
.editor, editor {
width: 90%;
min-height: 400px;
/* overflow: hidden; */
/* height: 100%; */
}
body {
background: #232327;
background: -moz-radial-gradient(center, circle cover, #373a4c 0%, #232327 100%);
background: -webkit-gradient(radial, center center, 0px, center center, 100%, color-stop(0%, #373a4c), color-stop(100%, #232327));
background: -webkit-radial-gradient(center, circle cover, #373a4c 0%, #232327 100%);
background: -o-radial-gradient(center, circle cover, #373a4c 0%, #232327 100%);
background: -ms-radial-gradient(center, circle cover, #373a4c 0%, #232327 100%);
background: radial-gradient(center, circle cover, #373a4c 0%, #232327 100%);
}
</style>
</head>
<body>
<div class="reveal has-">
<div class="slides">
<!--
Refs
https://gist.github.com/acutmore/9d2ce837f019608f26ff54e0b1c23d6e (4-bit VM)
https://github.com/pirix-gh/medium/blob/master/types-curry-ramda/src/index.ts good TS kung-fu
https://github.com/Microsoft/TypeScript/issues/14833 TypeScripts Type System is Turing Complete
-->
<!-- Section: Intro -->
<section>
<p>This is an interactive presentation. Press "s" to open the speaker view.</p>
<aside class="notes">
Because this presentation contains live coding, it doesn't make any sense unless you have the speaker notes handy ;)<br>
<br>
Snippets of code will be provided here and you can copy-paste them in the editor when needed.
</aside>
</section>
<section>
<aside class="notes">
Start here
</aside>
</section>
<section>
<div style="display: flex; flex-direction: column;">
<img src="./imgs/thumbnail.png" alt="" style="display: block; width: 60%; margin: auto;">
<h2 style="display: block; margin-top: 40px;">10 Things You Did Not Know TypeScript Could Do</h2>
</div>
<aside class="notes">
Thank you for coming to this talk entitled "10 Things you did not know TS could do".<br>
And thank you to those who bit on the clickbait by the way.<br>
</aside>
</section>
<section>
<div class="h-layout">
<div>
<img src="./imgs/loved.png" alt="" style="display: block">
</div>
<div>
<img src="./imgs/wanted.png" alt="" style="display: block">
</div>
</div>
<aside class="notes">
Today we'll talk about TypeScript.
According to a popular developer survey, TS is the 3rd most loved language and 4th most wanted.
(StackOverflow 2019 developer survey)
</aside>
</section>
<section>
<div class="h-layout">
<div style="text-align: left; padding-top: 20px; padding-left: 100px">
<img src="./imgs/me.png" alt="" style="border: none; width: 200px; background-color: transparent; box-shadow: none">
<p>Hadrien Milano</p>
<p>Software Engineer, UI</p>
<div style="float: left">@</div>
<img src="./imgs/appdynamics.png" alt="" style="width: 200px; margin: auto; border: none">
</div>
<div>
<img class="fragment" src="./imgs/dashboard.png" alt="" style="display: block; margin: auto; border: none; width: 700px; margin-top: 100px">
</div>
</div>
<aside class="notes">
My name is Hadrien Milano, I work at AppDynamics as a UI dev. We build fancy dashboards like this one.<br>
<br>
While I like pretty UIs like this one, the thing that really drives me is pretty code.<br>
And this explains why I love TypeScript: an attempt to bring order into the chaos that is JavaScript.
</aside>
</section>
<section>
<div style="position: absolute; margin-left: 420px">
<img class="fragment" src="./imgs/pavement.jpg" alt="" style="display: block; margin: auto; border: none; width: 500px; margin-top: 40px">
</div>
<div style="position: absolute; margin-left: 410px">
<img class="fragment" src="./imgs/cookie.jpg" alt="" style="display: block; margin: auto; border: none; width: 500px; margin-top: 80px">
</div>
<div style="position: absolute; margin-left: 414px">
<img class="fragment" src="./imgs/coke.jpg" alt="" style="display: block; margin: auto; border: none; width: 600px; margin-top: 140px">
</div>
<div style="position: absolute; margin-left: 414px">
<img class="fragment" src="./imgs/simple.png" alt="" style="display: block; margin: auto; border: none; width: 600px; margin-top: 140px">
</div>
<div style="position: absolute; margin-left: 404px">
<img class="fragment" src="./imgs/complicated.png" alt="" style="display: block; margin: auto; border: none; width: 630px; margin-top: 120px">
</div>
<div style="position: absolute; margin-left: 380px">
<img class="fragment" src="./imgs/refinery.jpg" alt="" style="display: block; margin: auto; border: none; width: 700px; margin-top: 100px">
</div>
<div style="position: absolute; margin-left: 100px">
<img class="fragment" src="./imgs/github-pr.png" alt="" style="display: block; margin: auto; border: none; width: 1100px; margin-top: 300px">
</div>
<div style="position: absolute; margin-left: 420px">
<img class="fragment" src="./imgs/fuckyou.png" alt="" style="display: block; margin: auto; border: none; width: 600px; margin-top: 100px">
</div>
<aside class="notes">
Once in a while I'll see a piece of code which, although it works, could be improved.<br>
<br>
[3 slides]
<br>
So I set out to the task of improving it. I come up with a simple plan.<br>
<br>
And quickly I find that there is more to it than I initially thought.<br>
<br>
So I iterate and work around the different complications.<br>
<br>
After a while I end up with a monstruosity of TypeScript hacks and tricks to do just that one thing I wanted to do.<br>
I submit it for code review and then...<br>
My coworkers ask me to burn that code to hell.<br>
</aside>
</section>
<section>
<aside class="notes">
But this code is a testimony of a voyage to the edge of TypeScript.<br>
I can't let this go to waste.<br>
</aside>
</section>
<section>
<h2>Focus of this talk</h2>
<img src="./imgs/purpose.png" alt="" style="display: block; width: 60%; margin: auto;">
<aside class="notes">
And so this is what this presentation is about.<br>
To give this werid code an afterlife so you too can be transported to the edge of TypeScript, and in this process, learn more about this popular language.<br>
<br>
Obviously you will not become experts just watching this presentation, but you'll walk out with a better understanding of it.
</aside>
</section>
<!-- Section: fundamentals -->
<section>
<h2>Foundations</h2>
<p class="fragment">
<span style="color: #5b94ec">Types</span> + <span style="color: #e8d11d">JavaScript</span> =
<span style="color: #5b94ec">Type</span><span style="color: #e8d11d">Script</span>
</p>
<aside class="notes">
Before we get into the weird stuff, we need to start with the basics. Let's see how familiar this room is with TypeScript...<br>
<br>
[Poll the room]<br>
<br>
Let's quickly review the basics.
</aside>
</section>
<section>
<p>JS with types</p>
<editor data-trim>
let someNumber = 1;
someNumber = '2';
</editor>
<aside class="notes">
TS adds types to variables to maximize correctness of the code.<br>
This is valid JavaScript, but it's not valid TypeScript. TS, by default considers that variables don't change type.<br>
Notice that the error could be either in the first or the second line.<br>
Maybe I want this variable to be a number. Or I want it to be a string, or both!<br>
If I want both, I should write <pre>let someNumber: string | number = 1;</pre><br>
When I don't write any type annotation, TS infers the type from the right hand side.<br>
</aside>
</section>
<section>
<p>Type aliases</p>
<editor data-trim>
type MyString = string;
const someString: MyString = 'abc';
</editor>
<aside class="notes">
I can define a custom type as an alias for another type.
</aside>
</section>
<section>
<p>Object types</p>
<editor data-trim>
type User = {
age: number;
name: string;
isHuman: boolean;
};
</editor>
<aside class="notes">
Define a variable:
<pre>const user: User = {
age: 5,
isHuman: false,
name: 'wall-e'
}</pre>
TS helps with auto-completion.<br>
TS has a built-in concept for these object types: an interface.<br>
<pre>interface User { ... }</pre>
</aside>
</section>
<!-- Section: Intersection, Union, Conditional -->
<section>
<h2>Operators</h2>
<aside class="notes">
With what we've seen so far, you already know 60% of what you'll ever need in TS.<br><br>
But you are going to need operators to combine types and start doing interesting stuff.<br>
</aside>
</section>
<section>
<p>Intersection (mixins)</p>
<editor data-trim>
<hidden>
declare function getUser(): any;
</hidden>
type User = { username: string; }
type Admin = { admin: true }
type Moderator = { moderator: true }
let john: User & Admin & Moderator = getUser()
</editor>
<aside class="notes">
John is a user AND an admin AND a Moderator.<br>
If we inspect the type of john, we can see it has the properties of all types.<br>
</aside>
</section>
<section>
<p>Trick #1<br>Safe html strings.</p>
<editor data-trim style="height: 300px;">
<hidden>
declare function escapeHtmlString(s: string): string;
declare function getUserInput(): string;
</hidden>
type SafeString = string & { __isEscaped: true };
function sanitize(raw: string): SafeString {
return escapeHtmlString(raw) as SafeString;
}
function render(template: string, ...args: SafeString[]) { /* ... */ }
</editor>
<aside class="notes">
And this leads us to our first trick!<br>
As you know protecting against XSS is hard. It's easy to miss a spot, but one breach is enough to compromise your app's security.<br>
<br>
__isEscaped is a "pseudo type" or "virtual type". It doesn't exist at runtime.<br>
<pre>
const userName = sanitize(getUserInput());
render("Hello %name%", userName);
</pre>
</aside>
</section>
<section>
<p>Trick #1½</p>
<editor data-trim style="height: 300px;">
<hidden>
declare function escapeHtmlString(s: string): string;
declare function getUserInput(): string;
type SafeString = string & { __isEscaped: true };
function sanitize(raw: string): SafeString {
return escapeHtmlString(raw) as SafeString;
}
</hidden>
function html<T extends string[]>(body: TemplateStringsArray, ...args: string[]): string {
let builder = '';
// ...
return builder;
}
const userName = getUserInput();
html`Hello ${userName}!`; // "Hello John!"
</editor>
<aside class="notes"><pre>
This is a JS tagged template. In TS they are type-checked! <br>
Replace argument string[] with SafeString[] .
</pre></aside>
</section>
<section>
<p>Union</p>
<editor data-trim>
<hidden>
type User = { handle: string; };
type Admin = { admin: true };
type Moderator = { modo: true };
declare function getUser(): any;
</hidden>
function anyone(who: Admin | User) { /* ... */ }
let john: Admin = getUser();
anyone(john);
</editor>
<aside class="notes">
This functions accepts either an admin or a user.<br>
<br>
[Change the type of john to be User, this still works]
</aside>
</section>
<section>
<div class="h-layout">
<div style="min-width: 400px;">
<p style="margin-top: 40%">Trick #2<br>Type narrowing</p>
</div>
<editor data-trim>
<hidden>
</hidden>
interface HumanUser {
kind: 'human';
firstname: string;
lastname: string;
}
interface BotUser {
kind: 'bot';
handle: string;
}
type AnyUser = HumanUser | BotUser;
function greet(user: AnyUser): string {
}
</editor>
</div>
<aside class="notes">
This union is discriminated by the member "kind".<br>
<br>
In the function, the only accessible member is "kind".<br>
<br>
If I discriminate based on this value, I gain access to the other members!<br>
<pre>
if (user.kind === 'human') {
return `Hello ${user.firstname} ${user.lastname}!`;
} else {
return `0101000110 ${user.handle}`;
}</pre>
</aside>
</section>
<section>
<div class="h-layout">
<div style="min-width: 500px;">
<p style="margin-top: 50%">Trick #2½<br>Exhaustive matching (without return type)</p>
<p class="fragment">Bonus trick<br>Type-level error messages</p>
</div>
<editor data-trim>
<hidden>
interface HumanUser {
type: 'human';
firstname: string;
lastname: string;
}
interface BotUser {
type: 'bot';
handle: string;
}
interface AlienUser {
type: 'alien',
codename: string
}
type AnyUser = HumanUser | BotUser | AlienUser;
declare function postMessage(s: string): void;
</hidden>
function greet(user: AnyUser): void {
switch (user.type) {
case 'human':
postMessage(`Hello ${user.firstname} ${user.lastname}!`);
break;
case 'bot':
postMessage(`0101000110 ${user.handle}`);
break;
// Am I missing something?
}
}
</editor>
</div>
<aside class="notes">
TypeScript has a type which means "should never happen". It is called <pre>never</pre>.<br>
<br>
Declare this function and use it in the <pre>default</pre> block.
<pre>
function isSwitchExhaustive(a: never) {
throw new Error('Unexpected case');
}
</pre>
<br>
For type-level error messages, change function parameter to:
<pre>a: "ERROR: You are missing a case in this switch"</pre>
<br>
Why does this work?<br>
Because unions can always be written as <pre>A | B | ... | never</pre>.<br>
Never is what is left when you've removed everything from a union.
</aside>
</section>
<section>
<div class="h-layout">
<div style="min-width: 500px;">
<p style="margin-top: 50%">Trick #3<br>Exhaustive matching</p>
</div>
<editor data-trim>
<hidden>
interface HumanUser {
type: 'human';
firstname: string;
lastname: string;
}
interface BotUser {
type: 'bot';
handle: string;
}
</hidden>
interface AlienUser {
type: 'alien',
codename: string
}
type AnyUser = HumanUser | BotUser | AlienUser;
function greet(user: AnyUser): string {
switch (user.type) {
case 'human':
return `Hello ${user.firstname} ${user.lastname}!`;
case 'bot':
return `0101000110 ${user.handle}`;
}
}
</editor>
</div>
<aside class="notes">
Can you spot the mistake in this code snippet?
...missing a case for 'alien' type.
</aside>
</section>
<!-- <section>
What type is left when there is nothing left?
<pre><code data-trim>
type SomeUnion = A | B | C; // | never;
</code></pre>
</section>
<section>
<p>What type is left when there is nothing left?</p>
<editor data-trim style="height: 300px">
<hidden>
interface HumanUser {
type: 'human';
firstname: string;
lastname: string;
}
interface BotUser {
type: 'bot';
handle: string;
}
interface AlienUser {
type: 'alien',
codename: string
}
</hidden>
type AnyUser = HumanUser | BotUser | AlienUser | never;
const myNever: never = 123;
function blackHole(a: number): never {
throw new Error('Oh no!');
}
</editor>
<aside class="notes"><pre>
function notBlackHole(a: number): never {
if (a === 2) {
throw new Error('Oh no!');
}
}
</pre></aside>
</section> -->
<section>
<p>Conditional types</p>
<pre><code data-trim>
A extends B ? Yes : No;
</code></pre>
<aside class="notes">
The last tool we need in our toolbox before we can get serious.
</aside>
</section>
<section>
<p>Conditional types</p>
<editor data-trim>
type IsNumber<T> = T extends number ? 'A number' : 'Not a number';
type A = IsNumber<2>;
type B = IsNumber<'hello'>;
</editor>
<aside class="notes"></aside>
</section>
<section>
<p>Conditional type inference</p>
<editor data-trim>
type MyTuple = ['one', 'two'];
type T = MyTuple extends [any, infer Second] ? Second : never;
</editor>
<img class="fragment" src="./imgs/ReturnType.png" />
<aside class="notes">
We capture a type in the matching pattern, and then use it<br>
Note that the same thing could be done with
<pre>type T = MyTuple[1]</pre>
However, this can not be done without conditional type inference:
<br>
See this definition from the standard library extracts the return type of a function.
</aside>
</section>
<section>
<p>Let's get serious!</p>
</section>
<!-- Section: recursive types, working with tuples, Rest.ts -->
<section>
<p>HTTP API definition</p>
<editor data-trim style="min-height: 400px">
<hidden>
declare function createClient<T>(api: T): { [k in keyof T]: (params?: any) => Promise<any>};
declare function createServer<T>(api: T, server: { [k in keyof T]?: (req: { params: any }) => void});
</hidden>
// Shared
const api = {
getAllCats: 'GET /api/cats',
getCatByName: 'GET /api/cats/:name'
};
// Client
const client = createClient(api);
// Server
const server = createServer(api, {});
</editor>
<p class="fragment"><small>Not super TypeScript friendly...</small></p>
<aside class="notes">
You have a web application with a front-end and a back-end component.<br>
You want to share the API definition between the front and back to maximize the safety of this link.<br>
This would be a typical way to do it. A shared API definition, then helpers to create client and server implementations of that API.<br>
<br>
But this naive approach is not safe. Take this code:<br>
<pre>client.getCatByName({
name: 'Olinka'
})</pre>
The parameter "name" could as well be "id" and this would compile, but fail at runtime...<br>
<br>
For the server implementation<br>
<pre>{
getAllCats() {},
getCatByName(req) {
}
}</pre>
req.params isn't type-checked either...<br>
<br>
Problem: There is no way to link the parameter names to their usage.
</aside>
</section>
<section>
<p>What if...</p>
<editor data-trim style="min-height: 400px">
<hidden>
interface Endpoint<Params extends string> {
params: { [k in Params]: string; };
}
interface Api {
[k: string]: Endpoint<any>;
}
type HttpClient<T extends Api> = {
[k in keyof T]: (params: T[k]['params']) => void;
}
interface HttpRequest<T extends Endpoint<any>> {
params: T['params'];
}
type HttpServer<T extends Api> = {
[k in keyof T]?: (req: HttpRequest<T[k]>) => void;
}
declare function createClient<T extends Api>(def: T): HttpClient<T>;
declare function createServer<T extends Api>(def: T, serv: HttpServer<T>): void;
declare function GET(str: TemplateStringsArray): Endpoint<never>;
declare function GET<A extends string>(str: TemplateStringsArray, a: A): Endpoint<A>;
declare function GET<A extends string, B extends string>(str: TemplateStringsArray, a: A, b: B): Endpoint<A | B>;
</hidden>
const api = {
getAllCats: GET `/api/cats`,
getCatByName: GET `/api/cats/${'name'}`
};
const client = createClient(api);
const server = createServer(api, { });
</editor>
<aside class="notes">
Call endpoint with name.<br>
Change parameter, notice type error.<br>
Add second parameter<br>
</aside>
</section>
<section>
<p>Is this... magic?</p>
<editor data-trim style="min-height: 250px">
interface Endpoint<Params extends string> {
params: { [k in Params]: string; }
}
declare function GET<A extends string>(str: TemplateStringsArray, a: A): Endpoint<A>
</editor>
<p>No, it's TypeScript! (trick #5)</p>
<aside class="notes">
GET is a template tag. You can use it like this:<br>
<pre>const endpoint = GET `/cats/${'name'}/`</pre><br>
And now the string literal is captured in the type of <pre>endpoint</pre>!
<br>
But this doesn't work when you add a second parameter...<br>
<pre>const endpoint = GET `/cats/${'owner'}/${'name'}/`</pre>
</aside>
</section>
<section>
<img src="./imgs/runtypes.png" alt="" class="fragment" style="position: absolute; display: block; width: 400px; margin-left: 400px;">
<img src="./imgs/rxjs.png" alt="" class="fragment" style="position: absolute; display: block; width: 1000px; margin-left: 100px; margin-top: 100px">
<div style="position: relative">
</div>
<p>Hmmm...</p>
<editor data-trim style="min-height: 300px">
<hidden>
interface Endpoint<Params extends string> {
params: { [k in Params]: string; };
}
</hidden>
declare function GET<A extends string>(str: TemplateStringsArray, a: A): Endpoint<A>;
declare function GET<A extends string, B extends string>(str: TemplateStringsArray, a: A, b: B): Endpoint<A | B>;
declare function GET<A extends string, B extends string, C extends string>(str: TemplateStringsArray, a: A, b: B, c: C): Endpoint<A | B | C>;
declare function GET<A extends string, B extends string, C extends string, D extends string>(str: TemplateStringsArray, a: A, b: B, c: C, d: D): Endpoint<A | B | C | D>;
</editor>
<aside class="notes">
An easy solution is to declare a version of the function for many different number of arguments.<br>
But this is not DRY, and imposes a hard limit on how many arguments can be accepted, even though the underlying function can accept any number of arguments!<br>
<br>
But this seems to be the industry standard at the moment...
</aside>
</section>
<section>
<p>Problem:</p>
<pre><code data-trim>
let Flatten = [A, B, C, ...] -> A | B | C | ...
</code></pre>
<aside class="notes">
How to flatten a tuple?
</aside>
</section>
<section>
<p>First attempt</p>
<editor data-trim style="height: 100px;">
type Flatten<T extends any[]> =
</editor>
<div class="fragment">
<p>sub-problems:</p>
<ul>
<li>"Rest" of a tuple</li>
<li>Recursive types</li>
</ul>
</div>
<aside class="notes">
Naively, one would start with a conditional like this:
<pre>type Flatten<T extends any[]> = T extends [infer Frist, ...infer Rest] ? First | Flatten<T[Rest]> : T;</pre>
<br>
How do I get the rest of a tuple?<br>
How do I make a recursive type?
</aside>
</section>
<section>
<p>Rest of a tuple</p>
<editor data-trim style="min-height: 400px;">
type Tail<T extends any[]> = ;
type test = Tail<['a', 'b', 'c']>
</editor>
<aside class="notes">
Well known trick: Use function varargs.
<pre>type Tail<T extends any[]> = ((...args: T) => void) extends (head: any, ...tail: infer Tail) => void ? Tail : never;</pre>
</aside>
</section>
<section>
<p>Tuple utilities (trick #4)</p>
<editor data-trim style="min-height: 400px;">
type List<Data extends any[]> = (...tail: Data) => void;
type Push<El, list extends List<any>> = list extends List<infer Data> ? (head: El, ...tail: Data) => void : never;
type Pop<Head, Tail extends any[]> = (h: Head, ...tail: Tail) => void;
type Tuple<L extends List<any>> = L extends List<infer T> ? T : never;
</editor>
<aside class="notes">
Armed with this varargs exploit, we can devise a type-level list library.<br>
This is how you use it:<br>
<br>
Create a list:<br>
<pre>type MyList = List<['a', 'b', 'c']>;</pre>
Prepend an element to the list:<br>
<pre>type MyList2 = Push<'z', MyList>;</pre>
Remove an element from the list:<br>
<pre>type MyList3 = MyList2 extends Pop<any, infer Tail> ? Tail : never;</pre>
Get the first element:<br>
<pre>type MyHead = MyList2 extends Pop<infer Head, any> ? Head : never;</pre>
<br>
The usage of pop is a little convoluted, but you'll see why it works like this in a minute...
</aside>
</section>
<section>
<p>Tuple flattening problems</p>
<ul>
<li><span style="color:red;text-decoration:line-through"><span style="color: white">"Rest" of a tuple</span></span></li>
<li>Recursive types</li>
</ul>
</section>
<section>
<p>Recursive types</p><editor data-trim style="min-height: 400px;">
<hidden>
type List<DATA extends any[]> = (...tail: DATA) => void;
type Push<El, list extends List<any>> = list extends List<infer Data> ? (head: El, ...tail: Data) => void : never;
</hidden>
type Pop<Head, Tail extends any[]> = (h: Head, ...tail: Tail) => void;
type Flatten<T extends List<any>> = T extends Pop<infer Head, infer Tail>
? Head | Flatten<List<Tail>>
: never
type A = Flatten<List<['a', 'b', 'c']>>
</editor>
<aside class="notes">
Split the type into two cases: edge case and general case.
<pre>
type Flatten<T extends List<any>> = {
rec: T extends Pop<infer Head, infer Tail> ? Head | Flatten<List<Tail>> : never
end: never
};
</pre>
Here only one iteration is performed. Most of the list is still uncomputed. I can access the partial result by doing:
<pre>type A = Flatten<List<['a', 'b', 'c']>>['rec']</pre>
<br>
But this needs to happen on each level of the recursion, automatically.<br>
<br>
I can try<br>
<pre>type Flatten = { ... }['rec']</pre><br>
But now the type is detected as a circular reference again!<br>
And it makes sense: This recursion would be infinite, because I am never invoking the end case.<br>
I need an exit condition...<br>
<pre>
type Flatten<T extends List<any>> = {
tail: T extends Pop<infer Head, infer Tail> ? Head | Flatten<List<Tail>> : never;
end: never;
} [
T extends Pop<unknown, any> ? 'end' : 'tail'
];
</pre>
The conditional type confuses the cycle detection algorithm!<br>
<br>
As seen here: https://github.com/Microsoft/TypeScript/issues/14833
</aside>
</section>
<section>
<p>Trick #5: Recursive type</p>
<editor data-trim style="min-height: 400px;">
<hidden>
type List<DATA extends any[]> = (...tail: DATA) => void;
type Push<El, list extends List<any>> = list extends List<infer Data> ? (head: El, ...tail: Data) => void : never;
type Pop<Head, Tail extends any[]> = (h: Head, ...tail: Tail) => void;
</hidden>
type Flatten<T extends List<any>> = {
tail: T extends Pop<infer Head, infer Tail> ? Head | Flatten<List<Tail>> : never;
end: never;
} [
T extends Pop<unknown, any> ? 'end' : 'tail'
];
</editor>
<aside class="notes"></aside>
</section>
<section>
<p>Putting it all together</p>
<editor data-trim style="min-height: 500px;">
<hidden>
interface Endpoint<Params extends string> {
params: { [k in Params]: string; };
}
interface Api {
[k: string]: Endpoint<any>;
}
type HttpClient<T extends Api> = {
[k in keyof T]: (params: T[k]['params']) => void;
}
interface HttpRequest<T extends Endpoint<any>> {
params: T['params'];
}
type HttpServer<T extends Api> = {
[k in keyof T]?: (req: HttpRequest<T[k]>) => void;
}
declare function createClient<T extends Api>(def: T): HttpClient<T>;
declare function createServer<T extends Api>(def: T, serv: HttpServer<T>): void;
type List<DATA extends any[]> = (...tail: DATA) => void;
type Push<El, list extends List<any>> = list extends List<infer Data> ? (head: El, ...tail: Data) => void : never;
type Pop<Head, Tail extends any[]> = (h: Head, ...tail: Tail) => void;
type Flatten<T extends any[]> = FlattenRec<List<T>, 't'>['t'];
interface FlattenRec<T extends List<any>, k extends 't'> {
t: T extends Pop<infer Head, infer Tail> ?
unknown extends Head ? never : Head | FlattenRec<List<Tail>, k>[k] : never;
}
</hidden>
declare function GET<Args extends string[]>(str: TemplateStringsArray, ...args: Args): Endpoint<Flatten<Args>>;
const api = {
getAllCats: GET `/api/cats`,
getCatByName: GET `/api/cats/${'name'}`
};
const client = createClient(api);
const server = createServer(api, {});
</editor>
</section>
<section>
<img class="fragment" src="./imgs/i-love-it.jpg" alt="" style="display: block; width: 60%; margin: auto;">
<p class="fragment">More at <a href="https://github.com/hmil/rest.ts">https://github.com/hmil/rest.ts</a></p>
<aside class="notes">
We won by combining a variable-arguments hack and exploiting a limitation of the circular reference detection code!
</aside>
</section>
<!-- Section: Turing completeness? Lambda calculus -->
<section>
<p>TypeScript can do a lot...</p>
<p class="fragment">But can it do everything?</p>
<aside class="notes">
We can manipulate objects, tuples, etc...
But what about numbers? Math? String manipulation? What about other algorithms?
</aside>
</section>
<section>
<p>What is <em>everything</em>?</p>
<aside class="notes">
We must first define what _everything_ actually is.<br>
<br>
</aside>
</section>
<section>
<img src="./imgs/turing.jpg" alt="" style="display: inline-block; width: 400px">
<img src="./imgs/church.jpg" alt="" style="display: inline-block; width: 400px">
<aside class="notes">
Luckily for us, these guys in black and white figured it out already.<br>
<br>
In the 1930s, the question of computability was a hot topic (unlike today, when it's butchered at the end of JavaScript meetups).<br>
<br>
Alan Turing and Alonzo Church were studying models of computation in the early days...
</aside>
</section>
<section>
<p>What is <em>everything</em>?</p>
<div style="display: flex; flex-direction: row; align-items: center">
<img src="./imgs/turing-machine.jpg" alt=""/>
<div class="fragment" style="padding: 20px; font-size: 70px;"> ≡ </div>
<img src="./imgs/lambda-calculus.png" alt="" />
</div>
<aside class="notes">
Turing came up with a theoretical machine (now dubbed the Turing machine) which could "compute stuff".<br>
Meanwhile, Church devised a mathematical language that could also "compute stuff".<br>
<br>
They both tried to formalize what their respective systems could compute, in vain...<br>
Until one day, they figured that their models, as well as a third one which for some reason isn't as popupar as the two former, were equivalent.<br>
<br>
Since then, the benchmark for how powerful a logical tool is has been "can it simulate a turing machine"? If it can, it is called "Turing complete".<br>
<br>
It could as well have been "can it simulate lambda-calculus" and "lambda-complete" - since this is equivalent - but for some reason the version that stuck in history was the Turing one.
</aside>
</section>
<section>
<h2>Is TypeScript Turing Complete?</h2>
<p class="fragment">Can it simulate a turing machine?</p>
<aside class="notes">
So, we know TS is probably not more powerful than a Turing machine because:<br>
a. It runs inside a computer which is itself no more powerful than a T. machine<br>
b. This would be the biggest scientific breakthrough of the century so far.<br>
So the question really is, can TS simulate a Turing machine?
</aside>
</section>
<section>
<p>Can we implement lambda calculus in TypeScript?</p>
<h2 class="fragment">[NSFW]</h2>
<p class="fragment">Do not try this at <span style="text-decoration: line-through">home</span> work.</p>
<aside class="notes">
We'll use lambda calculus because it is a much better fit for our task than a turing machine.
</aside>
</section>
<section>
<div style="display: flex; flex-direction: row; justify-content: space-between">
<div>
Variable:
<pre style="width: 300px; text-align: center"><code data-trim>x</code></pre>
<pre class="fragment" style="width: 300px; text-align: center"><code data-trim>var x</code></pre>
</div>
<div>
Abstraction:
<pre style="width: 400px; text-align: center"><code data-trim>λx. <something></code></pre>
<pre class="fragment" style="width: 400px; text-align: center"><code data-trim>x => <something></code></pre>
</div>
<div>
Application:
<pre style="width: 500px; text-align: center"><code data-trim><something1> <something2></code></pre>
<pre class="fragment" style="width: 500px; text-align: center"><code data-trim><something1>(<something2>)</code></pre>
</div>
</div>
<!-- <img src="./imgs/lambda1.png" alt="" style="max-width: 50%">
<pre class="fragment"><code data-trim>
λx. λy. x y
(x: any) => (y: any) => x(y)
</code></pre> -->
<aside class="notes">
Lambda calculus is extremely simple. There are only 3 constructs in total:<br>
variablesl, abstractions and applications.<br>
A variable is like a variable in any old programing language.<br>
An abstraction can be thought of as a function in JS<br>
An application is what happens when you apply an expression to another expression (which hopefully evaluates to a function)<br>
<br>
Looking at this, it's easy to see that JavaScript is turing complete. We have here a direct mapping from lambda calculus to JavaScript.<br>
But this is not what we are looking for, we want to evaluate these expressions in the type system itself!
</aside>
</section>
<section>
<p>Example</p>
<pre><code data-trim>
(λx. x) y
= y
</code></pre>
<pre class="fragment"><code data-trim>
(λx. x x) (λy. y y)
(λx=(λy. y y). x x)
= (λy. y y) (λy. y y)
</code></pre>
<aside class="notes">
Let's take a look at some examples.
</aside>
</section>
<section>
<p>Example</p>
<pre><code data-trim>
0 = λf. λx. x
1 = λf. λx. f x
2 = λf. λx. f (f x)
SUCC = λn. λf. λx. f ((n f) x)
</code></pre>
<pre class="fragment"><code data-trim>SUCC 0 = (λn. λf. λx. f ((n f) x)) 0</code></pre>