英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论