将声明设置为TRUE时出现打字稿错误 [英] Typescript errors when setting declaration to TRUE

查看:145
本文介绍了将声明设置为TRUE时出现打字稿错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为我正在研究的Angular 2项目创建打字稿定义,以便它可以作为可导出的库.

I'm trying to create typescript definitions for a Angular 2 project I'm working on so that it can be an exportable library.

我有几种服务设置,它们将http请求返回到与以下内容非常相似的组件:

I have several services setup that return http requests to components all quite similar to the following:

public create(user:User) {
  return this.http.post(this._apiUrls.create,
    JSON.stringify(user), {
      headers: this.apiConfig.getApiHeaders()
    });
}

然后我从组件中调用类似这样的内容:

Which I then call from a component something like this:

Session.create(user).subscribe((res:Response) => {
  this.user = res.json().user
}); 

一切正常,直到我在tsconfig文件中将"declaration"设置为true为止,以便我可以创建打字稿定义文件.我的一些服务开始出现以下错误:

This all works fine until I turn 'declaration' to true in the tsconfig file so that I can create typescript definition files. I start to get the following errors for several of my services:

error TS4053: Return type of public method from exported class has or is using name 'Observable' from external module "node_modules/rxjs/Observable" but cannot be named.

我大部分都了解问题,但不知道解决方案.如果将Observable导入服务,则打字稿短绒将引发错误,因为从技术上讲,该文件未使用它.

I mostly understand the problem but I don't know a solution. If I import Observable into the service then the typescript linter will throw errors because technically it's not being used in that file.

来自Angular 1,这是我们在所有应用程序中采用的类似范例,用于将我们的代码分开,但是也许我需要更改Angular 2中的方法?我看了很多其他Angular 2示例,它们也都以类似的方式完成了.

Coming from Angular 1 this was a similar paradigm we took in all ours apps to break our code apart but maybe I need to change the approach in Angular 2? I've looked at lots of other Angular 2 examples and they have all done it in a similar way also.

推荐答案

到目前为止,编译器不会自动为您在声明文件中导入类型.

As of today, the compiler won't automatically import types for you in a declaration file.

目前最好的解决方法是手动禁用导入的棉绒规则,或者导入类型并使用显式的类型注释,以便棉绒将其标记为使用情况.

The best workaround for now is to manually disable your lint rules for the import, or to import the type and use an explicit type annotation so that the linter marks it as a usage.

换句话说

// Explicit import of 'Observable' so that '.d.ts' files
// can be generated correctly.
import { Observable } from "node_modules/rxjs/Observable";

// Explicit use of 'Observable' to satisfy your linter.
public create(user: User): Observable {
  return this.http.post(this._apiUrls.create,
     JSON.stringify(user), {
       headers: this.apiConfig.getApiHeaders()
    });
}

这篇关于将声明设置为TRUE时出现打字稿错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆