microsoft / TypeScript

TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
https://www.typescriptlang.org
Apache License 2.0
101.12k stars 12.5k forks source link

Extend type predicate inference to work with certain type variables #59088

Open ethanresnick opened 4 months ago

ethanresnick commented 4 months ago

🔍 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

type Thing = A | B | C
type A = { kind: 'A', id: string, /* ... */ }
type B = { kind: 'B', id: string, /* ... */ }
type C = { kind: 'C', id: string, /* ... */ }

function filterByKind<T extends Thing['kind']>(things: Thing[], kind: T) {
  return things.filter((it) => it.kind === kind);
}

// The below would ideally be typed as `A[]`, as the function passed to 
// `filter` would have an inferred type predicate of `it is Thing & { kind: T }`
const x = filterByKind([], 'A');

const someKind = Math.random() < .5 ? 'A' : 'B';
const y = filterByKind([], someKind); // (A | B)[]

💻 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

Andarist commented 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?

ethanresnick commented 4 months ago

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).

RyanCavanaugh commented 4 months ago

@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