4 ms·
That's basically case 1, right? The compiler knows which type is being used at each call site, so it can generate a separate function for each type in the union
by jakelazaroff 5y ago
That's basically case 1, right? The compiler knows which type is being used at each call site, so it can generate a separate function for each type in the union and eliminate the type check/dead branches.
I guess the exception would be if you have a non-homogenous array that you try to map over. In that case there's probably no way around boxing the values.
- xg15 5y agoFor consts and function arguments yes, I think. But you could have some mutable variable or field whose value depends on runtime state. In that case, you could have an actual polymorphic type.
- epolanski 5y agoBut the previous example isn't that case. if (c.type === 'a') { /* c is of type A here */ } This is dynamic typing, this code is checked at runtime, and it's leveraged statically.
- xg15 5y agoYes, that's correct. In the GP example, c was const, so the type can be determined at compile time.
- simulate-me 5y agoI was writing TypeScript, where const just means the variable is not reassigned. For instance this is valid: const c: C = Math.random() < 0.5 ? { type: 'a' } : { type: 'b' }.
- xg15 5y agoAh, I'm sorry. You're right of course!
- deleted 5y ago[deleted]