Reputation: 10617
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
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