how to use string literal types in interfaces with mongoose?

Viewed 234

I want to define a field property and limit it to certain values. I was hoping for something like this:

class ITopic extends Document {
  public status?: string = "testing" | "public"
}

that's not legal TS syntax so i tried putting a type above

type statusTypes = "testing" | "ready"
class ITopic extends Document {
  public status?: statusTypes
}

This is legal typescript syntax, but breaks usage elsewhere in the app as the mongoose schemaDef only accepts types like String, not complex types:

const TopicSchema: Schema = new Schema({
status: { type: String },
)}

now elsewhere in my code I get errors like:

No overload matches this call.
  The last overload gave the following error.
    Argument of type '{ status: string; }' is not assignable to parameter of type 'FilterQuery<ITopic>'.
      Type '{ status: string; }' is not assignable to type '{ name?: Condition<string | undefined>; title?: Condition<string | undefined>; description?: Condition<string | undefined>; submitter?: Condition<string | undefined>; ... 60 more ...; validateSync?: ((pathsToValidate?: string[] | undefined, options?: any) => CallbackError) | ... 1 more ... | undefined; }'.
        Types of property 'status' are incompatible.
          Type 'string' is not assignable to type 'Condition<"testing" | "ready" | undefined>'.

this is interesting, where the type is actually internally a Condition

Types of property 'status' are incompatible.\n          
Type 'string' is not assignable to type 'Condition<\"testing\" | \"ready\" | undefined>'.",

So I'm wondering what's the best way to allow only a limited set of string values in a mongoose model, like an ENUM.

0 Answers
Related