0

I have an argument of type

((element: any) => Type<any>) | Type<any> 

and if it is a Function i need to call it, other wise just use the Type as-is

getType(element: any, type: ((element: any) => Type<any>) | Type<any>): Type<any> { return isFunctionNotType(type) ? type(element) : type; } 

Unfortunately I am not sure how to write the isFunctionNotType method. There is an isType method in @angular/core/src/type but whenever I try using that I get the following error during compilation

ERROR in C:/Users/xxxxxx/xxxxxx/xxxxxx/dist/xxxxxx/fesm5/angular-utils.js Module not found: Error: Can't resolve '@angular/core/src/type' in 'C:\Users\xxxxxx\xxxxxx\xxxxxx\dist\xxxxxx\fesm5' 

Is there some way to get this working without having to break up the type variable into two?

EDIT: I should point out since people seem to be missing the point here. In angular Type extends Function, and at run-time you will not be able to tell them apart just by doing an instanceof or something like that.

1
  • I don't think Angular should be the resource for type-checking, especially since you're already using Typescript. Either use the instanceof operator, or do some kind of duck-typing using a function that returns Type is SpecificType, which will satisfy the compiler. See this question for more info. Commented Aug 22, 2019 at 17:46

2 Answers 2

0

(typeof callback === "function")

I would check if its a function, then do something for the other type with an 'else'.

Sign up to request clarification or add additional context in comments.

Comments

0
type TypeFn<T> = (element: T) => Type<T>; function isFunctionNotType<T>(type: TypeFn<T> | Type<T>): type is TypeFn<T> { return typeof type === 'function'; } function getType<T>(element: T, type: TypeFn<T> | Type<T>): Type<T> { return isFunctionNotType(type) ? type(element) : type; } 

isFunctionNotType return type type is TypeFn<T> give a boolean AND will infer the return type.

Note that I added generics, it may be inappropriate so remove them in this case.

2 Comments

Unfortunately typeof SomeType returns "function" since Type extends Function (I am talking about the Type interface from @angular/core)
I see, so there is no clean way to do the check. A solution may be to wrap TypeFn in an object, or anything that could disting its.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.