Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript get type, that type guard function checks

I have a type guard function for type User. How do I extract the type, that this function "guards"? Using ReturnType<typeof isUser> obviously does not work since the return type of the function is boolean, not User.

type User = {
  username: string
}

function isUser(value: unknown): value is User {
  return value !== null && typeof value === "object" && "username" in value;
}

type GuardType<T> = ...

// something like this?
type GuardTypeOfUserGuard = GuardType<typeof isUser>; // should be `User`
like image 424
nyarthan Avatar asked Nov 01 '25 07:11

nyarthan


1 Answers

You can perform conditional type inference on a similarly-shaped user-defined type guard function type:

type GuardType<T> = 
  T extends (x: any, ...rest: any) => x is infer U ? U : never;

By "similarly-shaped" I mean that this will only match such functions where the first argument is the one guarded. Anyway, you can check that it works:

type GuardTypeOfUserGuard = GuardType<typeof isUser>; 
// type GuardTypeOfUserGuard = User

Playground link to code

like image 181
jcalz Avatar answered Nov 03 '25 03:11

jcalz