首页 > 解决方案 > 在命名空间内找不到名称

问题描述

我试图在打字稿中分离接口和实现,所以我选择使用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 中抱怨这一点。我遵循文档中有关命名空间的内容,但它对我不起作用。应该如何解决这个问题?

标签: node.jstypescriptnamespaceses6-modules

解决方案


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) 替换(“轻量级、可移植项目”部分)。

相关:如何在 TypeScriptModules 中使用带有导入的命名空间与命名空间:组织大型打字稿项目的正确方法是什么?.


推荐阅读