【发布时间】:2017-10-06 12:21:22
【问题描述】:
与 AngularJs 的使用相比,索引签名的使用更令人担忧,但我认为这是一个关键问题,需要通过 TypeScript 类型以某种方式解决。
随着 TypeScript 2.4 的弱类型添加,@types/angularjs IController 开始抱怨弱类型,修复(此时唯一可能的修复)是添加索引签名,如此处所引用:
https://github.com/DefinitelyTyped/DefinitelyTyped/issues/17257 https://github.com/DefinitelyTyped/DefinitelyTyped/pull/17303
但在此更改之前,TypeScript 错误将有助于确保当您使用对象中的属性键入 IController 时,它会(适当地)抱怨您错过了定义属性,这是使 TypeScript 成为很棒的语言(至少是 IMO)。
这是一个使用简化的 AngularJs 1.5 组件的直接示例:
let MyComponent = function(): angular.IComponentOptions {
return {
bindings: {},
controller: MyController,
controllerAs: 'vm',
}
}
interface IController extends angular.IController {
x: string;
}
function MyController(this: IController) {
let vm = this;
vm.x = "foo"; // OK
vm.x = 1; // ERROR: As expected due to the definition - great
// This next line would have complained before this,
// now it will let it thru unscathed, same with functions,
// arrays, etc. - this is the problem
vm.y = "bar"; // OK now, ERROR before
}
有没有办法既允许 AngularJs 的类型避免弱类型问题(这是有道理的),同时仍然允许正确检查子类型?
我个人认为,由于这个问题,应该尽可能避免使用索引签名,并且不是避免编译器错误的好方法(尽管目前可能是唯一的方法)。
谢谢
【问题讨论】:
标签: angularjs typescript