Open ethanresnick opened 4 months ago
This all works on existing narrowing capabilities. So, in a sense, you are not asking about a type predicate inference improvement but for a narrowing improvement. No narrowing happens today here:
type Thing = A | B | C;
type A = { kind: "A"; id: string /* ... */ };
type B = { kind: "B"; id: string /* ... */ };
type C = { kind: "C"; id: string /* ... */ };
function doStuffIfKind<T extends Thing["kind"]>(thing: Thing, kind: T) {
if (thing.kind === kind) {
thing;
// ^? (parameter) thing: Thing
}
}
What serializable type you'd expect to see here?
So, in a sense, you are not asking about a type predicate inference improvement but for a narrowing improvement.
Fair enough!
What serializable type you'd expect to see here?
I guess I'd expect to see Thing & { kind: T }
(which probably isn't particularly useful in the function body, but does become useful if it makes it into the inferred return type).
@ahejlsberg was kicking an idea around a while back where all narrowing would be done via intersection like what you're proposing there, which would make this work more or less automatically. I don't think we have a tracking issue for it yet though -- still some technical obstacles around e.g. how to handle negative narrowings
🔍 Search Terms
type predicate inference generic
✅ Viability Checklist
⭐ Suggestion
When a function would normally serve as a type predicate for a discriminated union, but the exact cases being selected by the type predicate are dictated by a type variable, it'd be nice if the type predicate could still be inferred.
📃 Motivating Example
💻 Use Cases
I think this comes up somewhat rarely, and the workaround is to simply manually write out the generic type predicate, but, at my company, we did find cases like this when we looked at our type predicates as part of upgrading to TS 5.5