我使用 typescript 和 durandal 作为概念证明,老实说它们并没有凝胶化。
最近我正在尝试解决以下智能感知错误:
“无法将 calendarServiceImport 类型转换为 ICalendarService”
///<reference path="service/CalendarService.ts"/>
import calendarServiceImport = require("service/CalendarService");
var calendarService: ICalendarService;
calendarService = calendarServiceImport;
对于 Durandal,导入调用应该是 DI 调用并且应该是一个实例,但 typescript 解析器认为它应该是一个类型。
这是我尝试导入的代码:
/// <reference path="../contracts/ICalendarService.ts"/>
/// <reference path="../../configure.d.ts"/>
import configuration = require('viewmodels/configure')
class CalendarService implements ICalendarService {
private NumberOfDaysToSync : number;
constructor() {
}
getCalendarNames(): string[] {
return ["My Calendar","My Other Calendar"];
}
pullLatestSchedule(calendarName : string) {
}
}
export = CalendarService;
我可以消除错误,但随后我会引入逻辑错误,这更糟糕,因为那样它就会成为应用程序错误。
例如。将以下行替换:calendarService = calendarServiceImport;
为 calendarService = new calendarServiceImport();
但没有任何意义,因为我将第二次实例化该对象。
如何解决此错误?
最佳答案
由于 TypeScript 和 Durandal 对 require
的语义存在分歧(“导入此”与“导入此的新实例”),因此您需要在某处添加强制转换。
选项 1——在消费地点转换:
import calendarServiceImport = require("service/CalendarService");
var calendarService = <ICalendarService><any>calendarServiceImport;
选项 2 - 在导出站点转换:
import configuration = require('viewmodels/configure')
class CalendarService implements ICalendarService {
private NumberOfDaysToSync : number;
constructor() {
}
getCalendarNames(): string[] {
return ["My Calendar","My Other Calendar"];
}
pullLatestSchedule(calendarName : string) {
}
}
var instance = <ICalendarService><any>CalendarService;
export = instance;
关于javascript - 如何在 typescript 中导入对象而不触发智能感知?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23505755/