Extract type guard function type being guarded similarly to ReturnType

I have a type guard function like this one:

function isSomething(object: object): object is { id: string; } {
  return 'id' in object;
}

I would like to get the type { id: string; } like so:

type HasId = Magic<typeof isSomething>; // { id: string; }
type NotIt = ReturnType<typeof isSomething>; // boolean

Using ReturnType I get boolean.

Is there a way to extract the type being guarded in TypeScript?

Upvotes: 0

Views: 87

Answers (1)

Dawid Rusnak
Dawid Rusnak

Reputation: 642

You may use Type Inference (infer) to extract the type.

function isSomething(object: object): object is { id: string; } {
  return 'id' in object;
}

type GuardType<T> = T extends (o: any) => o is infer A ? A : never;
type X = GuardType<typeof isSomething>;

Upvotes: 3

Related Questions