Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting TS interface from mongoose schema without the 'Document'?

I'm using ts-mongoose so I can define interfaces + schemas for my data in 1 single place. Then I'm exporting them as a mongoose schema + actual interface.

The issue I'm having is finding a simple 1 step way of extracting that interface without all the 'Document' methods & properties.

I have these two compiled together from a github issue:

type ExtractDoc<T> = T extends Model<infer U> ? U : never;
type ExtractI<T> = Pick<T, Exclude<keyof T, keyof Document>>;

and I've been trying to write a reusable thing to combine the two:

export type ExtractInterface<T> = ExtractI<ExtractDoc<T>>;

But then when I try to use it with a Schema:

export type IExternalUser = ExtractInterface<ExternalUser>;

is throwing out: refers to a value, but is being used as a type here.

But if I do it with the extra 2 steps, it will work and everything is peachy.

Is there a way to extract the clean interface with just 1 call to a reusable type?

like image 363
SebastianG Avatar asked Sep 02 '25 06:09

SebastianG


1 Answers

you need to put a <typeof> before the <ExternalUser>

export type IExternalUser = ExtractInterface<typeof ExternalUser>;

like image 91
Alexvdan Avatar answered Sep 04 '25 22:09

Alexvdan