1
+ // Path: src/01-intro/08-typescript.ts
2
+
3
+ let myName = 'Packt' ;
4
+ // myName = 10; // commented to avoid error
5
+
6
+ /* Type inference */
7
+ let age = 20 ; // number
8
+ let existsFlag = true ; // boolean
9
+ let language = 'JavaScript' ; // string
10
+
11
+ let favoriteLanguage : string ;
12
+ let langs = [ 'JavaScript' , 'Ruby' , 'Python' ] ;
13
+ favoriteLanguage = langs [ 0 ] ;
14
+
15
+ /* Interfaces as type */
16
+ interface Person {
17
+ name : string ;
18
+ age : number ;
19
+ }
20
+
21
+ function printName ( person : Person ) {
22
+ console . log ( person . name ) ;
23
+ }
24
+
25
+ const john = { name : 'John' , age : 21 } ;
26
+ const mary = { name : 'Mary' , age : 21 , phone : '123-45678' } ;
27
+ printName ( john ) ;
28
+ printName ( mary ) ;
29
+
30
+ /* Interfaces as OO */
31
+ interface Comparable < T > {
32
+ compareTo ( b : T ) : number ;
33
+ }
34
+
35
+ class MyObject implements Comparable < MyObject > {
36
+ age : number ;
37
+
38
+ constructor ( age : number ) {
39
+ this . age = age ;
40
+ }
41
+
42
+ compareTo ( b : MyObject ) : number {
43
+ if ( this . age === b . age ) {
44
+ return 0 ;
45
+ }
46
+ return this . age > b . age ? 1 : - 1 ;
47
+ }
48
+ }
49
+
50
+ /* Enums */
51
+ enum Compare {
52
+ LESS_THAN = - 1 ,
53
+ BIGGER_THAN = 1 ,
54
+ EQUALS = 0
55
+ }
56
+
57
+ function compareTo ( a : MyObject , b : MyObject ) : number {
58
+ if ( a . age === b . age ) {
59
+ return Compare . EQUALS ;
60
+ }
61
+ return a . age > b . age ? Compare . BIGGER_THAN : Compare . LESS_THAN ;
62
+ }
63
+
64
+ /* Type aliases */
65
+ type UserID = string ;
66
+ type User = {
67
+ id : UserID ;
68
+ name : string ;
69
+ }
0 commit comments