angular 2 typescript 无法在环境上下文中声明实现

angular 2 typescript An implementation cannot be declared in ambient contexts

我是打字稿的新手,我正在尝试为 angular 2 指令创建一个函数。 谁能用 n00bs 的语言解释当我用 Gulp 编译时试图告诉我的错误是什么?

An implementation cannot be declared in ambient contexts

该消息适用于 offset()toggler()

import { Directive, ElementRef, Input } from '@angular/core';

@Directive({
  selector: 'offCanvas',
  inputs: ['target', 'toggle', 'placement', 'autohide', 'recalc', 'disableScrolling', 'modal', 'canvas', 'exclude'],
  host: {
    '(click)': 'Click()'
  }
})

export class OffCanvas {  
  @Input('target') target: string;
  @Input('canvas') canvas: string;
  @Input('state') state: string;
  @Input('exclude') exclude: string;
  @Input('placement') placement: string;
  @Input('toggle') toggle: boolean;
  @Input('autohide') autohide: boolean;
  @Input('recalc') recalc: boolean;
  @Input('disableScrolling') disableScrolling: boolean;
  @Input('modal') modal: boolean;

  public offset() {
    switch (this.placement) {
      case 'left':
      case 'right':  return (<HTMLElement>document.querySelector(this.target)).offsetWidth
      case 'top':
      case 'bottom': return (<HTMLElement>document.querySelector(this.target)).offsetHeight
    }
  }

  public toggler() {
    if (this.state === 'slide-in' || this.state === 'slide-out') return
    this[this.state === 'slid' ? 'hide' : 'show']()
  }

  Click() {
    this.toggler()
  }
}

An implementation cannot be declared in ambient contexts

您很可能将文件命名为 foo.d.ts 而不是 foo.ts。这将它标记为一个声明文件(关于 https://basarat.gitbooks.io/typescript/content/docs/types/ambient/d.ts.html 的更多信息)并且你不能将 logic 放入其中,因为你正在 declaring 什么逻辑存在于别处。

我遇到了同样的错误并通过键入以下内容修复了它:

npm install --save typescript@latest

package.json 现在有最新的 ts 版本,ts 编译器是 2.2.2。

错误 TS1183:无法在环境上下文中声明实现。 解决方案:删除节点模块并重新安装。

我通过以下方式修复了它: npm 安装 rxjs

我认为这发生在我身上,因为我不小心编辑了 node_modules 中的一个文件。这为我修复了它:

rm -r node_modules
npm install

我 运行 跨越了这个相当不寻常的编译时 Typescript 错误 error TS1183: An implementation cannot be declared in ambient contexts.

它是在我 copy/pasted 一些具有 export declare class 的源代码之后开始的。我注意到当我将其更改为 export class 时,此错误消失了。

改变这个:

export declare class Foo {
}

为此:

export class Foo {
}

我在 constructor 实施中遇到了这个问题。所以,基本上,我们需要在定义 class.

时避免实现 {...}

而不是这个:

declare module MyModlue {
  class MyClass {
      constructor(type: string) {
        // implementation
    };
  }
}

我这样做了:

declare module MyModlue {
  class MyClass {
    constructor(type: string); // notice that it doesn't have implementation
  }
}