Skip to content

Instantly share code, notes, and snippets.

@aviatesk
Created August 4, 2021 09:59
Show Gist options
  • Save aviatesk/8ab85df1140843919d418241034f41cf to your computer and use it in GitHub Desktop.
Save aviatesk/8ab85df1140843919d418241034f41cf to your computer and use it in GitHub Desktop.
memory effect on TypeScript's type safety
interface Foo {
bar: undefined | Bar
}
interface Bar {
baz: string
}
export function getbaz(foo: Foo) {
if (foo.bar) {
somewrite(foo)
return foo.bar.baz // XXX will result in error
}
return undefined
}
function somewrite(foo: Foo) {
if (Math.random() < 0.5) {
foo.bar = undefined
}
}
const foo = {bar: {baz: "hi"}}
console.log(getbaz(foo))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment