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

查看:27
本文介绍了将声明设置为 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 文件中将声明"设置为 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 导入到服务中,那么 typescript linter 会抛出错误,因为从技术上讲,它没有在该文件中使用.

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.

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

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天全站免登陆