Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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`

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading