Skip to content

Commit 38c52cf

Browse files
authored
Update typeGuard.md
1 parent f51a3d4 commit 38c52cf

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

docs/types/typeGuard.md

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,3 +168,37 @@ function doStuff(arg: Foo | Bar) {
168168
doStuff({ foo: 123, common: '123' });
169169
doStuff({ bar: 123, common: '123' });
170170
```
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+
function immediate(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:
194+
195+
```js
196+
// Type Guard
197+
if (foo.bar) {
198+
console.log(foo.bar.baz); // Okay
199+
const bar = foo.bar;
200+
functionDoingSomeStuff(() => {
201+
console.log(bar.baz); // Okay
202+
});
203+
}
204+
```

0 commit comments

Comments
 (0)