Brad
Brad

Reputation: 41

Returning a strongly typed promiseValue from angular $modalInstance with TypeScript

TypeScript newb Question. I'm trying to return a strongly typed promise from angular's $modalInstance.

I have something similar to:

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)

Upvotes: 1

Views: 436

Answers (2)

Brad
Brad

Reputation: 41

I actually had to wrap the $modal and $modalInstance services to take a type T. The above answer (which I had initially tried) will not work because the $modalInstance result is a promise of type 'any'. The wrapped $modalInstance is a promise of type 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>;
}

Upvotes: 1

Andreas Turku
Andreas Turku

Reputation: 413

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

Upvotes: 0

Related Questions