abi
abi7mo ago

Type-narrowing/covariance/contravariance

Why is it that 5 has type 5 but {five:5} has type {five:number} and not {five:5}?
17 Replies
ioB
ioB7mo ago
if you do {five:5} as const it will have the type { five: 5 } iirc
abi
abiOP7mo ago
Yes! I use as const a lot 🙂 Kinda what led me to ask the question 😄
ioB
ioB7mo ago
well I think the assumption is just that you mean it to be a number this is a big open question in type systems lots of haskell theory you could read up on here for context
abi
abiOP7mo ago
Heheh, I wrote my masters thesis project in Haskell
ioB
ioB7mo ago
it turns out that making a type system usuable involves making some not-obvious tradeoffs
abi
abiOP7mo ago
It sure is not obvious to me 🙂 But something in the back of my brain says it has to do with covariance/contravariance/etc. I just can't really formulate it myself. The same is true for e.g. [5] becoming number[]
ioB
ioB7mo ago
yeah that's a fun one here's another fun one:
const x = [];
x.push(5);
const x = [];
x.push(5);
is a type error because x has type never[]
abi
abiOP7mo ago
Rightly so, if you ask me 😄
ioB
ioB7mo ago
rust makes a tradeoff here where
let mut x = Vec::new();
x.push(1);
let mut x = Vec::new();
x.push(1);
actually just works ™️
abi
abiOP7mo ago
That's interesting What would you say the trade-off is? Just out of curiosity
ioB
ioB7mo ago
In this case, there's a usability/compile time tradeoff you make here like I wish the typescript one just worked, but making type inference just work in that case is expensive
abi
abiOP7mo ago
Exactly
ioB
ioB7mo ago
swift took this to the extreme and some people consider that to be its biggest mistake https://danielchasehooper.com/posts/why-swift-is-slow/
abi
abiOP7mo ago
It does? Are you referring to extensions?
ioB
ioB7mo ago
worth a read if you're curious
abi
abiOP7mo ago
Ah right, I loved that about Swift when I coded iOS
abi
abiOP7mo ago
This can't be correct
No description

Did you find this page helpful?