0

How is possible that this code compiles, it should fail with the type thrown after the first if

class Optional<T> {}

class Some<T> extends Optional<T> {
  constructor(public t: T) {
      super()
  }
}

function div(n: number, d: number): Optional<number> {
  if (d === 0.0) {
    return "IMPOSSIBLE"
  }
  return new Some(d / n)
}

console.log(div(1, 0))

1 Answer 1

2

Because TypeScript has a structual type system which means it judges type compatibility not by name but by its properties, so an empty class is essentially any but for few types like null or undefined, since it requires none property

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.