Typescript get type, that type guard function checks

Advertisements

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`

>Solution :

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

Leave a ReplyCancel reply