blop blop - 1 month ago 15
TypeScript Question

Use imports inside interface definition

I'm having a strange problem with typescript interfaces. Because I'm using mongoose models I need to define one, but for some reason it's not recognising things that I have explicitly imported. This part works fine:

export interface ITrip extends mongoose.Document {
//
}

export var TripSchema = new mongoose.Schema({
//
});

export var Trip = mongoose.model<ITrip>('Trip', TripSchema);


Now, I'm defining another interface, that has an array of Trip. I need this for subdocuments.

import {Trip, ITrip} from '../trips/trip.model';

export interface IFeed extends mongoose.Document {
lastSnapshot: {
trips: [Trip]
}
}


The TS compiler gives this error:
feed.ts(12,13): error TS2304: Cannot find name 'Trip'.
(referring to
trips: [Trip]
). It doesn't say that the import failed or anything. I can even use trip inside the same file to create new objects
var a = new Trip({});
without problem. Inside the interface it breaks.

Answer

Trip isn't a type, it's a variable, so you can do this:

let t = Trip;
let t2 = new Trip({});

But you can't do this:

let t: Trip;

You should change it to typeof Trip:

export interface IFeed extends mongoose.Document {
    lastSnapshot: {
        trips: [typeof Trip]
    }
}

Also, if you want IFeed.lastSnapshot.trips to be an array, then it should be:

trips: typeof Trip[]

What you declared is a tuple of one item.


Edit

With an object the assignment is always the same (both js and ts):

let o = {
    key: "value"
}

But when declaring types in typescript then you're not dealing with values:

interface A {
    key: string;
}

let o: A = {
    key: "value"
}

In the mongoose documentation they are using only javascript so all of their examples don't include the type declarations.