I’m encountering difficulty with TypeScript’s type inference when trying to determine the left-hand side type of a variable assigned to the result of a method call on an Iterable class. Here’s a simplified version of the issue:
const iterable1 = [1, 2, 3, 4, 5];
const collectAsSet: Set<number> = intoIterable(iterable1).collect(); // expected { 1, 2, 3, 4, 5 };
const iterable2 = [6, 7, 8, 9, 10];
const collectAsArray: number[] = intoIterable(iterable2).collect(); // expected [6, 7, 8, 9, 10];
To achieve this, I’m trying to somehow infer the types Set<number> and number[] from the return object of the intoIterable method. Is it possible to do this directly within the method of the intoIterable return object?
p.s. I know how to implement it by passing parameters to .collect(). However, I’m interested in exploring a method that accomplishes this within the method chaining approach.
function x<T>() {
return {} as T & (T extends { foo: number } ? { foo: 42 } : { foo: "42" });
}
const n: { foo: number } = x();
const s: { foo: string } = x();
console.log("N", n, "S", s);