没有完美的方法来引用“不是函数的对象”这样的类型,因为这需要 true减法类型,而 TypeScript 中不存在这种情况(至少从 3.1 开始)。
一种足够简单的解决方法是查看Function界面并描述一些绝对是的东西not a Function
,但它会匹配您可能遇到的大多数非函数对象。例子:
type NotAFunction = { [k: string]: unknown } & ({ bind?: never } | { call?: never });
这意味着“具有一些未指定键的对象,该对象要么缺少bind
财产或call
属性”。让我们看看它的行为如何:
const okayObject: NotAFunction = { a: "hey", b: 2, c: true };
const notOkayObject: NotAFunction = () => {}; // error, call is not undefined
Good.
这是一种解决方法而不是直接的解决方案的原因是某些非函数可能同时具有call
and a bind
属性,只是巧合,你会得到一个不希望的错误:
const surprisinglyNotOkay: NotAFunction = {
publication: "magazine",
bind: "staples",
call: "867-5309",
fax: null
}; // error, call is not undefined
如果您确实需要支持此类对象,您可以更改NotAFunction
变得更复杂并排除更少的非功能,但定义可能总会出现错误。由你决定你想走多远.