Skip to content

Instantly share code, notes, and snippets.

@itsMapleLeaf
Last active January 8, 2019 16:09
Show Gist options
  • Save itsMapleLeaf/076e0cc2e47f819b6eb6686ff984714f to your computer and use it in GitHub Desktop.
Save itsMapleLeaf/076e0cc2e47f819b6eb6686ff984714f to your computer and use it in GitHub Desktop.
.forEach vs. for..of in TS
let value: string | undefined
const items: any[] = []
if (value) {
items.forEach(() => {
// value is string | undefined
// TS can't (and shouldn't) know whether this callback is synchronous; `value` might have changed
value
})
for (const item of items) {
// value is string
// for..of loops are _always_ synchronous,
// so we know for sure that it won't have changed at this point
value
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment