Home > Software engineering >  Typescript two interfaces referencing each other, is it possible?
Typescript two interfaces referencing each other, is it possible?

Time:01-11

I am currently having a problem where I have two interfaces, UserProfile & Interest. The code is as follows for the two interfaces:

export default interface UserProfile {
    userProfileId: string,
    rep: number,
    pfpUrl: string,
    bio: string,
    experience: "beginner" | "intermediate" | "expert",
    country: string,
    height: number,
    weight: number,
    age: number,
    createdAt: Date,
    updatedAt: Date,
    userId: string,
    interests: Interest[]
}

export default interface Interest {
    interestId: string;
    name: string;
    createdAt: Date;
    updatedAt: Date;
    UserProfiles: UserProfile[]
}

As shown both has a many to many relationship with each other. The problem is that an error occurs stating that 'Interest' cant be found maybe because it has not been initialized yet. If that is the case how would we solve such problem? I am just matching the structure of what my API returns. My API returns those structure when fetching for either UserProfile or Interest

CodePudding user response:

The issue is that you're exporting both as default. Make one or both of your interfaces a regular named export and your problem should be solved.

  • Related