Search code examples
node.jstypescriptsyntax

Why do I get "Cannot find name '...'.ts(2304)" when I try to import/implement an interface in TypeScript?


I have defined an interface like below:

interface IChat {
  chat_id: Buffer;
  user_id: Buffer;
  admin_id: Buffer;
  user_name: string;
  admin_name: string;
  start_time: string;
  ending_time: string;
  messages: IMessage[];
}

interface IMessage {
  type: boolean; // 0 = admin , 1 = user
  message: string;
}

export { IChat };

Then I tried to use it within another file, but when I try to import and implement it like following:

import { IChat } from "../models/chat";


class Chats implements IChat {
  chat_id: Buffer;
  user_id: Buffer;
  admin_id: Buffer;
  user_name: string;
  admin_name: string;
  start_time: string;
  ending_time: string;
  messages: IMessage[];

I get this error:

Cannot find name 'IMessage'.ts(2304)

Solution

  • Just export/import it like you do for IChat.

    In your model file:

    export { IChat, IMessage };
    

    In your consuming file:

    import { IChat, IMessage } from "../models/chat";
    

    If you want to use a given type, beyond what's provided by core TypeScript/JavaScript/DOM, you have to import it explicitly. There's no automatic transitive import of types in TypeScript. If there was, your local namespace would be polluted to the point where it would be almost impossible to come up with an unused type name.