0

I am trying to create an object with subobjects in typescript. I'm trying to set up a mongoose schema as shown in this question.

If I define the object and subobjects as interfaces, I'm not able to use them in a constant that I can set as a mongoose schema.

So is there a way for me to not have to type out the whole subobject twice, once in the interfaces and once in the constant?

export interface Pizza {
    flavor: String;
    size: String;    
}

export interface Menu {
    pizza: Pizza
}

// Doesn't work
export const Menu = {
    store: String,
    menu: Menu  
}

// Works
export const Menu = {
    store: String,
    menu: {
        pizza: {
            flavor: String,
            size: String
        }
    }  
}

// What I really want
export const Menu = new mongoose.Schema({
    store: String,
    menu: Menu
});

// What I'm doing right now
export const Menu =  new mongoose.Schema({
    store: String,
    menu: {
        pizza: {
            flavor: String,
            size: String
        }
    }  
});
Community
  • 1
  • 1
Aarmora
  • 1,143
  • 1
  • 13
  • 26
  • There are too `Menu`s in your code. You want it to be an interface or a variable/const? – Nitzan Tomer May 13 '16 at 17:45
  • @NitzanTomer I just have them both there for comparison, illustrating what I want and what I have to use. I want to use the interface in the const or a method of achieving the same thing. – Aarmora May 13 '16 at 17:50

1 Answers1

1

I haven't worked with mongoose, but from what I've seen, constructing a mongoose.Schema requires real objects, what you're trying to pass are typescript interfaces which only exist until the compilation, after that the resulting javascript doesn't include them.

Maybe this is what you're looking for:

export class Pizza {
    flavor: String;
    size: String;    
}

export class Menu {
    pizza: Pizza
}

export const Menu = new mongoose.Schema({
    store: String,
    menu: Menu
});

I just turned your interfaces into classes which are present in the compiled javascript.

Nitzan Tomer
  • 155,636
  • 47
  • 315
  • 299