在命名空间内找不到名称

Cannot find name inside namespace

我试图在 typescript 中分离接口和实现,所以我选择使用 module 功能。但是,即使我使用 <reference path=.../>,我也总是收到 Cannot find name。这是我的代码:

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 ... /> 语法;
  • 不要一起使用命名空间和模块。 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) {
    }
}

您必须定义 a tsconfig.json file. The /// <reference ... /> statement is replaced by a configuration file (tsconfig.json) since TypeScript 1.5(部分 "Lightweight, portable projects")。

相关: and .