【问题标题】:How to import an object in typescript without tripping intellisense?如何在打字稿中导入对象而不触发智能感知?
【发布时间】:2014-05-06 22:43:07
【问题描述】:

我正在使用带有 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(); 但没有意义,因为我将第二次实例化该对象。

如何解决这个错误?

【问题讨论】:

    标签: javascript requirejs typescript durandal durandal-2.0


    【解决方案1】:

    由于 TypeScript 和 Durandal 对 require 的语义存在分歧(“导入 this”与“导入 this 的新实例”),因此您需要在某处添加强制转换。

    选项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;
    

    【讨论】:

    • 你先生,真棒!特维姆!!!我选择了后来的解决方案,总是在生产现场巩固复杂性。 - 更具凝聚力。
    猜你喜欢
    • 2016-04-28
    • 1970-01-01
    • 2020-10-04
    • 2017-06-28
    • 2017-06-18
    • 2013-12-25
    • 2019-12-11
    • 2019-12-23
    • 1970-01-01
    相关资源
    最近更新 更多