【问题标题】:Cannot find name inside namespace在命名空间内找不到名称
【发布时间】:2019-08-28 07:05:51
【问题描述】:

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

IUserService.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() {}
}

然后 tsc 总是在 UserService.ts 中抱怨 Cannot find name IUserService。我遵循文档中有关命名空间的内容,但它对我不起作用。应该如何解决这个问题?

【问题讨论】:

  • 但是 2019 年坚持教 ///namespace 的糟糕教程在哪里?
  • 这是官方教程here
  • 您的代码将在浏览器或 Node.js 上执行?如果这是浏览器,你是用 Webpack 还是 Require.js 或者其他工具?
  • 这将在 node.js 上执行。

标签: node.js typescript namespaces es6-modules


【解决方案1】:

两个建议from the TypeScript handbook:

  • 不要使用/// &lt;reference ... /&gt; 语法;
  • 不要同时使用命名空间和模块。 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/// &lt;reference ... /&gt; 语句替换为配置文件 (tsconfig.json) since TypeScript 1.5“轻量级、可移植项目”部分)。

相关:How to use namespaces with import in TypeScriptModules vs. Namespaces: What is the correct way to organize a large typescript project?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-14
    • 2017-07-12
    相关资源
    最近更新 更多