如何在TypeScript中声明仅包含对象而不包含函数的类型 [英] How to declare a type in TypeScript that only includes objects and not functions
问题描述
在TypeScript中是否可以通过某种方式定义类型,使其仅包含对象但不包含函数?
Is it in TypeScript somehow possible to define a type so that it only includes objects but not functions?
示例:
type T = { [name: string]: any } // How to modify this to only accepts objects???
const t: T = () => {} // <- This should not work after modification
感谢您的帮助.
推荐答案
没有完美的方法来引用诸如不是函数的对象"之类的类型,因为这将需要真实的
There's no perfect way to refer to a type like "an object which is not a function", since that would require true subtraction types, and that doesn't exist in TypeScript (as of 3.1 at least).
一个简单的解决方法是查看 Function
接口,并描述肯定不是 和Function
的东西,但它会匹配您可能会遇到的大多数非功能对象.示例:
One easy-enough workaround is to look at the Function
interface and describe something which is definitely not a Function
, but which would match most non-function objects you're likely to run into. Example:
type NotAFunction = { [k: string]: unknown } & ({ bind?: never } | { call?: never });
这意味着具有一些未指定键的对象,该对象缺少bind
属性或call
属性".让我们看看它的行为:
That means "an object with some unspecified keys, which is either missing a bind
property or a call
property". Let's see how it behaves:
const okayObject: NotAFunction = { a: "hey", b: 2, c: true };
const notOkayObject: NotAFunction = () => {}; // error, call is not undefined
好.
这是一种解决方法,而不是简单的解决方案,其原因是某些非功能可能同时具有call
和bind
属性,并且您会遇到不希望出现的错误:>
The reason that this is a workaround and not a straightforward solution is that some non-functions might have both a call
and a bind
property, just by coincidence, and you'll get an undesirable error:
const surprisinglyNotOkay: NotAFunction = {
publication: "magazine",
bind: "staples",
call: "867-5309",
fax: null
}; // error, call is not undefined
如果您确实需要支持此类对象,则可以将NotAFunction
更改为更复杂,并排除更少的非功能,但是可能总会出现定义错误的情况.由您决定您想走多远.
If you really need to support such objects you can change NotAFunction
to be more complicated and exclude fewer non-functions, but there will likely always be something the definition gets wrong. It's up to you how far you want to go.
希望有帮助.祝你好运!
Hope that helps. Good luck!
这篇关于如何在TypeScript中声明仅包含对象而不包含函数的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!