This sounds like a great opportunity to use a union type (TypeScript 1.4 or higher) - an example from this blog post :
type StringPromise = string | ng.IPromise<string>; module App { export interface MyInterface { foo: ng.IPromise<string>; } class MyClass implements MyInterface { private _fooDeferred: ng.IDeferred<string>; constructor(private $q: ng.IQService) { this._fooDeferred = this.$q.defer(); } get foo(): StringPromise { return this._fooDeferred.promise; } set foo(value: StringPromise) { this._fooDeferred.resolve(value); } } }
Notes:
- You will need to use type protection devices if you want to use a specific type from a union type
- You may need to use type statements in some cases.
Type guard
The following is an example of type protection
if (typeof value === 'string') { // the type of value inside this if statement is // string, rather than StringPromise } else { // the type of value inside this else statement is // ng.IPromise<string>, rather than StringPromise }
Type approval
If necessary, you can approve the following types:
var prom = <string> value;
Fenton
source share