打字稿:$ rootScope(Angularjs)上不存在属性

Shy*_*ikh 7 service visual-studio angularjs typescript

在Typescript中向rootscope添加值时出错.

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

    addValueToRoot=()=>{
       this.rootScope.val1 = "something";    //Error: Property doesn't exist on the IRootScopeService
    }
}
Run Code Online (Sandbox Code Playgroud)

mue*_*hdo 18

那是因为(正如编译器所说)val1不存在ng.IRootScopeService.您需要扩展它以适应您的需求,例如

interface MyRootScope extends ng.IRootScopeService {
  val1: string
}
Run Code Online (Sandbox Code Playgroud)

然后你可以在你的班级中使用这个界面:

class TestClass {
  this.rootScope: MyRootScope;
  ...
}
Run Code Online (Sandbox Code Playgroud)


Ste*_*ung 7

您可能正在使用TypeScript 1.6,它开始捕获此类错误.

我通常做的是:

  1. 使用 $rootScope: any

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

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

No.3增加了该类型的附加属性的允许.您甚至可以将其保存在类型名称下以供重用:

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

$rootScope: ng.IRootScopeService & IExpandable;
Run Code Online (Sandbox Code Playgroud)