angular 2 typescript An implementation cannot be declared in ambient contexts

poashoas picture poashoas · May 26, 2016 · Viewed 25.3k times · Source

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()
  }
}

Answer

basarat picture basarat · May 26, 2016

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.