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.

SamYonnou
  • 2,068
  • 1
  • 19
  • 23
  • 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](https://stackoverflow.com/questions/12789231/class-type-check) for more info. – Enioluwa Segun Aug 22 '19 at 17:46

2 Answers2

0

(typeof callback === "function")

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

timi95
  • 368
  • 6
  • 23
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.

Richard Haddad
  • 904
  • 6
  • 13
  • Unfortunately `typeof SomeType` returns `"function"` since `Type extends Function` (I am talking about the `Type` interface from `@angular/core`) – SamYonnou Aug 22 '19 at 20:29
  • 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. – Richard Haddad Aug 22 '19 at 21:00