node.js - 在命名空间内找不到名称
问题描述
我试图在打字稿中分离接口和实现,所以我选择使用module
功能。但是,Cannot find name
即使我使用<reference path=.../>
. 这是我的代码:
用户服务.ts
namespace Service {
export interface IUserService {
login(username: string, password: string): void;
}
}
用户服务.ts
/// <reference path="./IUserService.ts" />
namespace Service {
export class UserService implements IUserService {
constructor() {}
}
Cannot find name IUserService
然后 tsc 总是在 UserService.ts 中抱怨这一点。我遵循文档中有关命名空间的内容,但它对我不起作用。应该如何解决这个问题?
解决方案
TypeScript 手册中的两条建议:
- 不要使用
/// <reference ... />
语法; - 不要同时使用命名空间和模块。Node.js 已经提供了模块,所以你不需要命名空间。
这是一个解决方案:
// IUserService.d.ts
export interface IUserService {
login(username: string, password: string): void;
}
// UserService.ts
import { IUserService } from "./IUserService";
export class UserService implements IUserService {
constructor() {
}
login(username: string, password: string) {
}
}
您必须定义一个tsconfig.json
文件。从 TypeScript 1.5 开始,该/// <reference ... />
语句被配置文件 (tsconfig.json) 替换(“轻量级、可移植项目”部分)。
相关:如何在 TypeScript和Modules 中使用带有导入的命名空间与命名空间:组织大型打字稿项目的正确方法是什么?.
推荐阅读
- javascript - 反应 this.props.title 为空!!为什么?
- android - android.view.InflateException: Binary XML file line #18: Binary XML file line #18: Error inflating class Button
- typescript - 什么是快速而肮脏的扩展/分配?
- python - 如何使用 Python 将 WebP 图像转换为 Gif?
- java - 有效证书上的 JDK 11 SSL 错误(在以前的版本中工作)
- azure - 我在 Windows CMD“stat: path too long for Windows”中得到这个错误——Azure cli
- cmake - CMake:在 openmpi 上选择 mpich
- tensorflow - “负采样”如何提高 word2vec 中的单词表示质量?
- javascript - 如果页面中有焦点输入密码元素,则 HTML5 拖动不适用于 Chrome
- python - SpaCy,在管道期间应用扩展