[英]How to tell apart Type from Function?
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 如果它是一个函数,我需要调用它,否则请按原样使用Type
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. 不幸的是,我不确定如何编写isFunctionNotType
方法。 There is an isType
method in @angular/core/src/type
but whenever I try using that I get the following error during compilation @angular/core/src/type
有一个isType
方法,但是每当我尝试使用它时,在编译过程中都会出现以下错误
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? 是否有某种方法可以使此工作有效而不必将type
变量分解为两个?
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. 在angular Type
扩展Function
,在运行时,您将无法仅通过执行instanceof
或类似操作来区分它们。
(typeof callback === "function") (typeof回调===“函数”)
I would check if its a function, then do something for the other type with an 'else'. 我会检查它是否有功能,然后用“ else”为其他类型做一些事情。
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. isFunctionNotType
返回类型的type is TypeFn<T>
给出一个布尔值,并将推断返回类型。
Note that I added generics, it may be inappropriate so remove them in this case. 请注意,我添加了泛型,可能不合适,因此在这种情况下将其删除。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.