sindresorhus / type-fest

A collection of essential TypeScript types
Creative Commons Zero v1.0 Universal
14.35k stars 545 forks source link

Proposal: Predicate inferer #973

Open emmbm opened 1 week ago

emmbm commented 1 week ago

Type description + examples

With typescript now supporting predicate inference for guard functions without the need for explicitly specifying a is clause, it could be interesting to provide a simple helper that allows to get the inferred predicate for any guard function.

Ex.:

function isValid(value: string | number | null | undefined | false) {
  return value != null && value !== false;
} // : value is string | number

type Valid = Predicate<typeof isValid> // string | number

Type source

export type Predicate<T> = T extends (x: any) => x is infer U ? U : never;

Search existing types and issues first

Upvote & Fund

Fund with Polar

sindresorhus commented 1 week ago

Sounds useful, but the name is slightly confusing. The type extracts the inferred guard type, but a name like Predicate makes it sound like it's for making predicates. Maybe something like GuardType or ExtractGuard?

emmbm commented 1 week ago

I agree Predicate is probably not the best naming, but I don't think derivatives of Guard sound right either since the guard is technically the check, not it's resulting assertion. Maybe GuardedType or just Guarded?

fregante commented 1 week ago

This type would be similar to ReturnType so maybe it should follow its naming.