Reputation: 75
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))
Upvotes: 0
Views: 47
Reputation: 951
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
Upvotes: 2