You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/types/typeGuard.md
+34Lines changed: 34 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -168,3 +168,37 @@ function doStuff(arg: Foo | Bar) {
168
168
doStuff({ foo: 123, common: '123' });
169
169
doStuff({ bar: 123, common: '123' });
170
170
```
171
+
172
+
### Type Guards and callbacks
173
+
174
+
TypeScript doesn't assume type guards remain active in callbacks as making this assumption is dangerous. e.g.
175
+
176
+
```js
177
+
// Example Setup
178
+
declare var foo:{bar?: {baz: string}};
179
+
functionimmediate(callback: ()=>void) {
180
+
callback();
181
+
}
182
+
183
+
184
+
// Type Guard
185
+
if (foo.bar) {
186
+
console.log(foo.bar.baz); // Okay
187
+
functionDoingSomeStuff(() => {
188
+
console.log(foo.bar.baz); // TS error: Object is possibly 'undefined'"
189
+
});
190
+
}
191
+
```
192
+
193
+
The fix is as easy as storing the inferred safe value in a local variable, automatically ensuring it doesn't get changed externally, and TypeScript can easily understand that:
0 commit comments