2

Angular's $http.defaults.transformRequest is defined as:

transformRequest?: IHttpRequestTransformer |IHttpRequestTransformer[];

Now I want to append an own transformer, so I need to check if this is already an array. I thought a simple typeguard with

function x(): angular.IHttpRequestTransformer[] { 
    if($http.defaults.transformRequest instanceof Array){
       return $http.defaults.transformRequest;
    }
}

would work, however, inside the if clause idea still thinks it is a union type. I also tried instanceof and $http.defaults.transformRequest.length === undefined, nothing worked.

Can anyone hint me in the right direction how I can tell IDEA that I've already ensured that $http.defaults.transformRequest is an array?

Thank!

rweng
  • 6,736
  • 7
  • 27
  • 30

1 Answers1

2

Type guards don't work on properties in TypeScript < 2.0. They only work on variables and parameters.

You will need to either put it in a variable and type guard that...

let transformRequest = $http.defaults.transformRequest;
if (transformRequest instanceof Array) {
    return transformRequest;
}

...or just use a type assertion:

if ($http.defaults.transformRequest instanceof Array) {
    return $http.defaults.transformRequest as IHttpRequestTransformer[];
}
David Sherret
  • 101,669
  • 28
  • 188
  • 178
  • transformRequest instanceof InterfaceType throws 'InterfaceType' only refers to a type, but is being used as a value here. [2693] – lohiarahul Jan 22 '19 at 21:10
  • @Iohiarahul it's not possible to use interfaces at runtime in TypeScript. Read more [here](https://stackoverflow.com/questions/14425568/interface-type-check-with-typescript). – David Sherret Jan 22 '19 at 21:20