Type narrowing not working for unions of tuples with object literals
See original GitHub issueIt’s not possible to narrow unions of tuples with object literals
TypeScript Version: 3.4.5, 3.5.0-rc
Search Terms: tuple narrow object literals
Code:
Narrowing tuples with primitive types works as expected:
type X = ["a", "c"] | ["b", "b"]
function bar(x: X) {
if (x[0] === "b") {
return x[1] === "c" // correctly narrows to "c", shows "condition always false"
}
}
However, when the tuple contains object literals, narrowing doesn’t work at all:
interface A { data: "a" }
interface B { data: "b" }
interface C { data: "c" }
type Y = [A, C] | [B, B]
function foo(y: Y) {
if (y[0].data === "b") {
return y[1].data === "c" // incorrectly narrows to "c" | "b"
}
}
Expected behavior:
The object literal within the tuple is correctly narrowed down to type B
Actual behavior:
The object literal is not narrowed, leaving it at type C | B
.
Playground Link: Link
Issue Analytics
- State:
- Created 4 years ago
- Reactions:1
- Comments:11 (5 by maintainers)
Top Results From Across the Web
Documentation - Narrowing - TypeScript
Notice we're using a union of string literal types: "circle" and "square" to tell us whether we should treat the shape as a...
Read more >Control flow not type-narrowing with union tuple?
There's no real workaround to this besides not destructuring, or doing destructuring after having narrowed the type sufficiently.
Read more >Type narrowing - mypy 0.991 documentation
def function(arg: object): if isinstance(arg, int): # Type is narrowed ... callable function can even split Union type for callable and non-callable parts:....
Read more >Google TypeScript Style Guide
Also consider named parameters using object literals and destructuring. ... Values of enum types (including unions of enum types and other types) must...
Read more >TypeScript Fundamentals - Joy of Code
Type Assertion Conversion; Literal Types; Literal Inference; Object Index Signatures; Type Narrowing; Type Guards; Type Predicates; Generics ...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
3 years old, still not fixed. Is this issue dead? It was first scheduled for 3.7 and then repeatedly rescheduled until it ended in the backlog. Fixing this would help in several use cases and greatly improve expressivity. I have several parts in my code base where I need to fall back to very generic types that are not helpful at all what could be a union of tuples.
I’d like to try this if no one started work