3 ms·
Note that you can only pass Cat to a Dog function if: * All fields of Dog are also present in Cat, with compatible type signatures * All functions of Dog are
by MaulingMonkey 7y ago
Note that you can only pass Cat to a Dog function if:
* All fields of Dog are also present in Cat, with compatible type signatures
* All functions of Dog are also present in Cat, with comaptible type signatures
"compatible type signatures" does seem to leave some suprising co/contravariance holes still when using wider union types, but C#/Java arrays also have co/contravariance holes and we don't automatically write off their entire type systems because of it. Or, well, at least I don't ;).
As a meaningless point of ancedata: Making these types sufficiently equivalent to fall through this type safety hole appears to be rare enough that I've never done so by accident - allowing me to be suprised by the article's example of passing a class Cat to a class Dog-accepting function being legal. While typescript has never been my primary dayjob, it's been a significant secondary part of my dayjob and hobby junk.
(EDIT: Minor clarifications)
- carlmr 7y agoC# has a great type system, but everything has ToString() and sometimes that doesn't output something sensible, and gets implicitly converted, leading to garbage. Still much better than working in C or some other weakly typed languages.
- Kinrany 7y agoAnother example of a hole: https://www.typescriptlang.org/v2/en/play#code/MYGwhgzhAECSB2wBOBTAti+AXFToG8AoaaAS0VQ2wAoAPALmngFc0AjXASkZfdwOIkyAM2jUsATwAOKAPaja0AIQBeFdADkvDkg2cBQoVgAWSWQHcmKSwFEkZpNQAGAEny0AvmRhhobyTLy0J4ANEyyWNC+2rhOnADcgiQehEnQqFjMSPDB0ADU0ACMicmEKYTkOEjCYMAo0ADKWEgIyOiYVQZkFO00DEysOtAAPtAQzeQA5twDfEiJ5cLMiFiksjnkbVRYdIzjSFNhm5QduIxNLT3bXDyD-EQkGVkbV6dIAHTHvTu0CWWpAHoAdA7A5GIUAEwAZm8UTGE3gkzC8AicJiSEIQOgTlaJ2wsWgABNZCgYCjIqQ0FIQN9ulUanVsRdcd9YoRgOsILIae8QLJJtQvttqBpIVCNMjrHBXvjHJx5fFoIQgA https://www.typescriptlang.org/v2/en/play#code/MYGwhgzhAECSB...