1
+ // Widening vs. non-widening literal types
2
+
3
+ function f1 ( ) {
4
+ const c1 = "hello" ; // Widening type "hello"
5
+ let v1 = c1 ; // Type string
6
+ const c2 = c1 ; // Widening type "hello"
7
+ let v2 = c2 ; // Type string
8
+ const c3 : "hello" = "hello" ; // Type "hello"
9
+ let v3 = c3 ; // Type "hello"
10
+ const c4 : "hello" = c1 ; // Type "hello"
11
+ let v4 = c4 ; // Type "hello"
12
+ }
13
+
14
+ function f2 ( cond : boolean ) {
15
+ const c1 = cond ? "foo" : "bar" ; // widening "foo" | widening "bar"
16
+ const c2 : "foo" | "bar" = c1 ; // "foo" | "bar"
17
+ const c3 = cond ? c1 : c2 ; // "foo" | "bar"
18
+ const c4 = cond ? c3 : "baz" ; // "foo" | "bar" | widening "baz"
19
+ const c5 : "foo" | "bar" | "baz" = c4 ; // "foo" | "bar" | "baz"
20
+ let v1 = c1 ; // string
21
+ let v2 = c2 ; // "foo" | "bar"
22
+ let v3 = c3 ; // "foo" | "bar"
23
+ let v4 = c4 ; // string
24
+ let v5 = c5 ; // "foo" | "bar" | "baz"
25
+ }
26
+
27
+ function f3 ( ) {
28
+ const c1 = 123 ; // Widening type 123
29
+ let v1 = c1 ; // Type number
30
+ const c2 = c1 ; // Widening type 123
31
+ let v2 = c2 ; // Type number
32
+ const c3 : 123 = 123 ; // Type 123
33
+ let v3 = c3 ; // Type 123
34
+ const c4 : 123 = c1 ; // Type 123
35
+ let v4 = c4 ; // Type 123
36
+ }
37
+
38
+ function f4 ( cond : boolean ) {
39
+ const c1 = cond ? 123 : 456 ; // widening 123 | widening 456
40
+ const c2 : 123 | 456 = c1 ; // 123 | 456
41
+ const c3 = cond ? c1 : c2 ; // 123 | 456
42
+ const c4 = cond ? c3 : 789 ; // 123 | 456 | widening 789
43
+ const c5 : 123 | 456 | 789 = c4 ; // 123 | 456 | 789
44
+ let v1 = c1 ; // number
45
+ let v2 = c2 ; // 123 | 456
46
+ let v3 = c3 ; // 123 | 456
47
+ let v4 = c4 ; // number
48
+ let v5 = c5 ; // 123 | 456 | 789
49
+ }
50
+
51
+ function f5 ( ) {
52
+ const c1 = "foo" ;
53
+ let v1 = c1 ;
54
+ const c2 : "foo" = "foo" ;
55
+ let v2 = c2 ;
56
+ const c3 = "foo" as "foo" ;
57
+ let v3 = c3 ;
58
+ const c4 = < "foo" > "foo" ;
59
+ let v4 = c4 ;
60
+ }
61
+
62
+ // Repro from #10898
63
+
64
+ type FAILURE = "FAILURE" ;
65
+ const FAILURE = "FAILURE" ;
66
+
67
+ type Result < T > = T | FAILURE ;
68
+
69
+ function doWork < T > ( ) : Result < T > {
70
+ return FAILURE ;
71
+ }
72
+
73
+ function isSuccess < T > ( result : Result < T > ) : result is T {
74
+ return ! isFailure ( result ) ;
75
+ }
76
+
77
+ function isFailure < T > ( result : Result < T > ) : result is FAILURE {
78
+ return result === FAILURE ;
79
+ }
80
+
81
+ function increment ( x : number ) : number {
82
+ return x + 1 ;
83
+ }
84
+
85
+ let result = doWork < number > ( ) ;
86
+
87
+ if ( isSuccess ( result ) ) {
88
+ increment ( result ) ;
89
+ }
90
+
91
+ // Repro from #10898
92
+
93
+ type TestEvent = "onmouseover" | "onmouseout" ;
94
+
95
+ function onMouseOver ( ) : TestEvent { return "onmouseover" ; }
96
+
97
+ let x = onMouseOver ( ) ;
0 commit comments