在命名空间内找不到名称

问题描述 投票:1回答:1

我正在尝试在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。我遵循文档中关于命名空间的说法,但它对我不起作用。应该解决这个问题的原因是什么?

node.js typescript namespaces es6-modules
1个回答
1
投票

两个建议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/// <reference ... />语句由配置文件(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?

© www.soinside.com 2019 - 2024. All rights reserved.