【发布时间】:2020-09-01 11:20:41
【问题描述】:
无论出于何种原因,TypeScript 都没有检测到实例函数的某些内容不可调用。
type Constructable = { new(...args: any[]): any }
function isClass(func: any) {
return (
typeof func === 'function' &&
/^class\s/.test(Function.prototype.toString.call(func))
)
}
function coerceOne(data: any, fn: Function | Constructable) {
if (isClass(fn)) {
const constructor = fn as Constructable
return new constructor(data)
} else {
return fn(data) // <-- ERROR
}
}
错误:
This expression is not callable.
No constituent of type 'Function | Constructable' is callable.(2349)
关于如何解决这个问题的任何想法?
【问题讨论】:
-
你在检查
func === 'function',是不是不等于? -
JavaScript 中的类是函数,所以是的,这个检查是必需的。
标签: typescript