我试图将打字稿中的接口和实现分开,所以我选择使用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 ... />语法;
不要将名称空间和模块一起使用。 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?

关于node.js - 在 namespace 内找不到名称,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55551283/

10-09 08:33
查看更多