Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: Property doesn't exist on the $rootScope (Angularjs)

Getting an error when adding a value to the rootscope in Typescript.

class TestClass{
   this.rootScope: ng.IRootScopeService;
   constructor($rootScope){
       this.rootScope = $rootScope;
    }

    addValueToRoot=()=>{
       this.rootScope.val1 = "something";    //Error: Property doesn't exist on the IRootScopeService
    }
}
like image 718
Shyamal Parikh Avatar asked Sep 28 '15 21:09

Shyamal Parikh


2 Answers

That is because (as the compiler says) val1 does not exist on ng.IRootScopeService. You need to extend it to adapt it to your needs, e.g.

interface MyRootScope extends ng.IRootScopeService {
  val1: string
}

Then you can just use this interface in your class:

class TestClass {
  this.rootScope: MyRootScope;
  ...
}
like image 177
muenchdo Avatar answered Sep 30 '22 22:09

muenchdo


You are probably using TypeScript 1.6 which starts catching this kind of errors.

What I usually do is either:

  1. use $rootScope: any

  2. do ($rootscope as any).val1 = ...

  3. use $rootScope: ng.IRootScopeService & { [name:string]: any };

No.3 adds allowance of additional properties to the type. You can even save it under a type name for reuse:

type IExpandable = { [name:string]:any };

$rootScope: ng.IRootScopeService & IExpandable;
like image 29
Stephen Chung Avatar answered Sep 30 '22 23:09

Stephen Chung