|
|
|
|
|
by esrauch
1109 days ago
|
|
Those don't change that the type system is structural; the type system is actually not fully safe if you use the things you mention, eg: class Dog { woof(){} }
class Cat { meow(){} }
function f(a: Dog|Cat) {
if (a instanceof Dog) {
a.woof()
} else {
a.meow()
}
}
let dogish = {woof: ()=>{}}
f(dogish)
This compiles because dogish is structurally a dog, the type system allows instanceof to narrow the type but "dogish instanceof Dog" is actually false, so at runtime this will crash after trying to call meow on dogish. |
|
Do this:
The neat thing about TypeScript's type system is that it's structural but you can pretty easily implement nominal types on top of it.(And if you only need compile-time checks, you can make typeName nullable; {typeName?:"Dog"} != {typeName?:"Cat"})