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

huangapple go评论64阅读模式
英文:

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

问题

你定义了一个接口如下:

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[];
}

然后尝试在另一个文件中使用它,但在导入和实现时出现了以下错误:

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[]; // 在此处出现错误
}

错误信息是:"Cannot find name 'IMessage'.ts(2304)"。这是因为在实现IChat接口时,你需要确保也导入了IMessage接口。请确保在导入中包括IMessage接口,以解决此问题。

英文:

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)

答案1

得分: 1

只需像对待 IChat 一样导出/导入即可。

在您的模型文件中:

export { IChat, IMessage };

在您的消费文件中:

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

如果您想要使用特定的类型,超出了核心的 TypeScript/JavaScript/DOM 提供的内容,您必须显式导入它。在 TypeScript 中没有自动的类型传递导入。如果有的话,您的本地命名空间将被污染到几乎不可能使用未使用的类型名称的程度。

英文:

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.

huangapple
  • 本文由 发表于 2023年4月13日 14:49:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/76002436.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定