@@ -30,7 +30,7 @@ const article: Element = {
30
30
const isSection = ( element : Element ) : element is Section =>
31
31
element . tagName === 'section'
32
32
33
- isElement ( )
33
+ expectType < false > ( isElement ( ) )
34
34
35
35
/* Missing parameters. */
36
36
expectError ( isElement < Section > ( ) )
@@ -133,3 +133,41 @@ convertElement()
133
133
convertElement ( null )
134
134
convertElement ( undefined )
135
135
expectError ( convertElement < Article > ( ) )
136
+
137
+ declare const node : unknown
138
+
139
+ /* Type assertion */
140
+ if ( isElement ( node ) ) {
141
+ expectType < Element > ( node )
142
+ }
143
+
144
+ if ( isElement ( node , ( node ) : node is Section => node . tagName === 'section' ) ) {
145
+ expectType < Section > ( node )
146
+ }
147
+
148
+ /**
149
+ * This test demonstrates that, while the test definitely asserts that `node`
150
+ * is an element, it asserts that it is *some* kind of element.
151
+ * If we’d define `node` as an `Element` in the if-branch (which is correct),
152
+ * TypeScript will think `node` is *not* an `Element` in the else-branch (which
153
+ * is incorrect).
154
+ * We can’t solve this in this project, but users can change their code (see
155
+ * next example).
156
+ */
157
+ if ( isElement ( node , ( node ) => node . children . length > 0 ) ) {
158
+ expectType < unknown > ( node )
159
+ } else {
160
+ expectType < unknown > ( node )
161
+ }
162
+
163
+ /**
164
+ * This is the suggested use of this package so TypeScript can infer what types
165
+ * it’s working with.
166
+ * This way, `node` as an `Element` in the if-branch, and it could still be an
167
+ * element (or something else) in the else-branch.
168
+ */
169
+ if ( isElement ( node ) && node . children . length > 0 ) {
170
+ expectType < Element > ( node )
171
+ } else {
172
+ expectType < unknown > ( node )
173
+ }
0 commit comments