我正在尝试在typescript中分离接口和实现,所以我选择使用module
功能。但是,即使我使用Cannot find name
,我总是收到<reference path=.../>
。这是我的代码:
IUserService.ts
namespace Service {
export interface IUserService {
login(username: string, password: string): void;
}
}
UserService.ts
/// <reference path="./IUserService.ts" />
namespace Service {
export class UserService implements IUserService {
constructor() {}
}
然后tsc总是在UserService.ts中抱怨Cannot find name IUserService
。我遵循文档中关于命名空间的说法,但它对我不起作用。应该解决这个问题的原因是什么?
两个建议from the TypeScript handbook:
/// <reference ... />
语法;这是一个解决方案:
// 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) {
}
}
你必须定义a tsconfig.json
file。 /// <reference ... />
语句由配置文件(tsconfig.json)since TypeScript 1.5(“轻量级,可移植项目”部分)替换。
相关:How to use namespaces with import in TypeScript和Modules vs. Namespaces: What is the correct way to organize a large typescript project?。