Repository navigation
Can't Narrow Destructured Tuple UnionΒ #56973
Copy link
Copy link
Closed
Labels
DuplicateAn existing issue was already createdAn existing issue was already created
Description
π Search Terms
Narrowing, Union, Destructuring, Tuple
π Version & Regression Information
- This is the behavior in every version I tried, and I reviewed the FAQ for entries about unions, instanceof and tuples.
β― Playground Link
π» Code
const VALUES = ["a1", "a2", "a3", "b1", "b2", "b3", "c1", "c2", "c3"] as const;
// Please ignore the non-sensical nature of these types. This is a simplified version of my real use case.
type Value = (typeof VALUES)[number];
type TransformFunction = (values: Value[]) => Value[];
type TransformDefinition = [RegExp] | [TransformFunction];
// This doesn't work, but seems like it should.
function errorExample(definition: TransformDefinition): TransformFunction {
let [condition] = definition;
if (condition instanceof RegExp) {
return () => VALUES.filter((value) => condition.test(value));
}
return condition;
}
// This works, and is almost the same thing
function successExample([condition]: TransformDefinition): TransformFunction {
if (condition instanceof RegExp) {
return () => VALUES.filter((value) => condition.test(value));
}
return condition;
}π Actual behavior
In the first example function, I get this error:
Property 'test' does not exist on type 'RegExp | TransformFunction'.
Property 'test' does not exist on type 'TransformFunction'.
π Expected behavior
Both examples should compile without an error
Additional information about the issue
My real use case is a bit more complex, and involves tuples with multiple values.
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
DuplicateAn existing issue was already createdAn existing issue was already created
Activity
MartinJohns commentedon Jan 7, 2024
Another duplicate of #9998.
fatcerberus commentedon Jan 7, 2024
Note that
errorExampleworks if you useconstinstead oflet.This case might be fixed by #56908
ahejlsberg commentedon Jan 8, 2024
This is indeed fixed by #56908 and is a duplicate of the many issues listed in that PR.
LandonSchropp commentedon Jan 9, 2024
Thank you!