Friday, August 26, 2022

TypeScript puzzle No.2 (easy)

Consider following code

class Foo {
  bar() {
    return 1
  }
}

const foo = new Foo
foo.bar()

Now consider that for some reason we want to include a type assertion, rather than just foo we want foo as Foo.

class Foo {
  bar() {
    return 1
  }
}

const foo = new Foo
(foo as Foo).bar()

Surprisingly, this one doesn't compile, the error points to the last line and says

Block-scoped variable 'foo' used before its declaration

As always, your goal is to explain the unexpected behavior here.

No comments: