使用TypeScript从angular $ modalInstance返回强类型的promiseValue

时间:2015-09-04 15:36:12

标签: angularjs modal-dialog typescript angular-promise

TypeScript newb问题。我试图从角度的$ modalInstance中返回强类型的承诺。

我有类似的东西:

this.$modal.open(options).result.then(result => {
    Currently result is type 'any'.  
    How do I cast it or affect it to be of type MyType?  (see below)         
});


interface myType {
    a: string,
    b: number
}

result: myType;
...

$modalInstance.close(this.result)

2 个答案:

答案 0 :(得分:1)

我实际上必须将$ modal和$ modalInstance服务包装为类型T.上面的答案(我最初尝试过)将无效,因为$ modalInstance结果是类型为'any'的承诺。包装的$ modalInstance是类型为T的承诺。

module my.interfaces {

export interface IMyModalService<T> {
    open(options: ng.ui.bootstrap.IModalSettings): IMyModalServiceInstance<T>;
}

export interface IMyModalScope<T> extends ng.ui.bootstrap.IModalScope {
    $dismiss(reason?: any): boolean;
    $close(result?: T): boolean;
}

export interface IMyModalServiceInstance<T> extends ng.ui.bootstrap.IModalServiceInstance {
    close(result?: T): void;
    dismiss(reason?: any): void;
    result: angular.IPromise<T>;
    opened: angular.IPromise<any>;
    rendered: angular.IPromise<any>;
}

答案 1 :(得分:0)

this.$modal.open(options).result.then((result: myType) => {
    Now result is declared to be of your type        
});