8 ms·
> In TypeScript you can assign an instance of one class to an instance of another as long as they have compatible fields. Fun fact: If you add a private field
by wwwigham 5y ago
> In TypeScript you can assign an instance of one class to an instance of another as long as they have compatible fields.
Fun fact: If you add a private field to a class it'll behave nominally in TS. This is because private fields kinda require nominal relations to function. So, in a way, it does support "switching" to nominal type checking for classes - the opt in is simply per-class.
- mirekrusin 5y agoIt won't do variance [0] right, will it? [0] https://flow.org/en/docs/lang/variance/ https://flow.org/en/docs/lang/variance/
- sizediterable 5y agoI think variance can be simulated by typing the private field as an existing covariant/contravariant/invariant type class CovariantFoo<T> { private phantom!: T } class ContravariantFoo<T> { private phantom!: (_: T) => void } class InvariantFoo<T> { private phantom!: (_: T) => T } (inspired by Rust [0]) [0] https://doc.rust-lang.org/nomicon/phantom-data.html https://doc.rust-lang.org/nomicon/phantom-data.html
- mirekrusin 5y agoBut variance depends on position where the value is used, not at the time of declaration, superclass/subclass at parameter/return value position can't be correctly encoded like this, can it?
- sizediterable 5y agoI think most languages define variance at type definition level, notable exceptions being Kotlin which supports both [0][1] and Flow. But yeah, TS doesn't support (variable-)declaration-site variance which I didn't realize you were asking in my previous answer. [0] https://kotlinlang.org/docs/generics.html#variance https://kotlinlang.org/docs/generics.html#variance [1] https://kotlinlang.org/docs/generics.html#declaration-site-variance https://kotlinlang.org/docs/generics.html#declaration-site-v...
- mirekrusin 5y agoDoesn't OCaml support it as well?
- sizediterable 5y agoI'm less familiar with OCaml and don't know off the top of my head. Doing a quick search I was only able to find references to type declaration variance [0], though I learned that Java also supports use-site variance too [1] [0] https://blog.janestreet.com/a-and-a/ https://blog.janestreet.com/a-and-a/ [1] https://blog.jooq.org/tag/use-site-variance/ https://blog.jooq.org/tag/use-site-variance/
- girvo 5y agoI believe this is conceptually similar to how "brands" can operate to add HKTs to TypeScript/Flow https://www.cl.cam.ac.uk/~jdy22/papers/lightweight-higher-kinded-polymorphism.pdf https://www.cl.cam.ac.uk/~jdy22/papers/lightweight-higher-ki... https://cs.emis.de/LIPIcs/volltexte/2015/5231/pdf/21_.pdf https://cs.emis.de/LIPIcs/volltexte/2015/5231/pdf/21_.pdf
- sizediterable 5y agoOh cool, hadn't realized this. Also thanks for your great work! I'm rooting for some of your exploratory PRs!