angular 2 typescript An implementation cannot be declared in ambient contexts

﹥>﹥吖頭↗ 提交于 2019-11-30 22:44:27

问题


I am new to typescript and I am trying to create a function for an angular 2 directive. Can anyone explain, in language for n00bs, what the error is trying to tell me when I am compiling with Gulp?

An implementation cannot be declared in ambient contexts

The message applies to offset() and 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()
  }
}

回答1:


An implementation cannot be declared in ambient contexts

You most probably have your file named as foo.d.ts instead of foo.ts. That marks it as a declaration file (more on that https://basarat.gitbooks.io/typescript/content/docs/types/ambient/d.ts.html) and you cannot put logic in these as you are declaring what logic exists elsewhere.




回答2:


I fixed it by doing: npm install rxjs




回答3:


I think this happened to me, because I accidentally edited one of the files in node_modules. This fixed it for me:

rm -r node_modules
npm install



回答4:


I had the same error and fixed it by typing:

npm install --save typescript@latest

package.json now has the latest ts version and ts compiler is 2.2.2.




回答5:


error TS1183: An implementation cannot be declared in ambient contexts. Solution :Removed node module and reinstall it.




回答6:


I ran across this rather unusual compile-time Typescript error error TS1183: An implementation cannot be declared in ambient contexts.

It started after I had copy/pasted some sourcecode that had export declare class. I noticed when I changed it to export class this error went away.

Change This:

export declare class Foo {
}

To This:

export class Foo {
}


来源:https://stackoverflow.com/questions/37448491/angular-2-typescript-an-implementation-cannot-be-declared-in-ambient-contexts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!