如何在 TypeScript 中声明一个只包含对象而不包含函数的类型
How to declare a type in TypeScript that only includes objects and not functions
是否可以在 TypeScript 中以某种方式定义一个类型,使其只包含对象而不包含函数?
示例:
type T = { [name: string]: any } // How to modify this to only accepts objects???
const t: T = () => {} // <- This should not work after modification
感谢您的帮助。
没有完美的方法来引用像 "an object which is not a function" 这样的类型,因为这需要 true subtraction types,并且在 TypeScript 中不存在(至少从 3.1 开始)。
一个足够简单的解决方法是查看 Function
interface 并描述一些绝对 不是 和 Function
但会匹配大多数非-您可能 运行 进入的功能对象。示例:
type NotAFunction = { [k: string]: unknown } & ({ bind?: never } | { call?: never });
即"an object with some unspecified keys, which is either missing a bind
property or a call
property"。让我们看看它的行为:
const okayObject: NotAFunction = { a: "hey", b: 2, c: true };
const notOkayObject: NotAFunction = () => {}; // error, call is not undefined
很好。
这是一种变通方法而不是直接解决方案的原因是一些非函数可能同时具有 call
和 bind
属性,只是巧合,并且你会得到一个不受欢迎的错误:
const surprisinglyNotOkay: NotAFunction = {
publication: "magazine",
bind: "staples",
call: "867-5309",
fax: null
}; // error, call is not undefined
如果您确实需要支持此类对象,您可以将 NotAFunction
更改为更复杂并排除更少的非函数,但定义可能总会出错。由你决定 how far you want to go.
希望对您有所帮助。祝你好运!
是否可以在 TypeScript 中以某种方式定义一个类型,使其只包含对象而不包含函数?
示例:
type T = { [name: string]: any } // How to modify this to only accepts objects???
const t: T = () => {} // <- This should not work after modification
感谢您的帮助。
没有完美的方法来引用像 "an object which is not a function" 这样的类型,因为这需要 true subtraction types,并且在 TypeScript 中不存在(至少从 3.1 开始)。
一个足够简单的解决方法是查看 Function
interface 并描述一些绝对 不是 和 Function
但会匹配大多数非-您可能 运行 进入的功能对象。示例:
type NotAFunction = { [k: string]: unknown } & ({ bind?: never } | { call?: never });
即"an object with some unspecified keys, which is either missing a bind
property or a call
property"。让我们看看它的行为:
const okayObject: NotAFunction = { a: "hey", b: 2, c: true };
const notOkayObject: NotAFunction = () => {}; // error, call is not undefined
很好。
这是一种变通方法而不是直接解决方案的原因是一些非函数可能同时具有 call
和 bind
属性,只是巧合,并且你会得到一个不受欢迎的错误:
const surprisinglyNotOkay: NotAFunction = {
publication: "magazine",
bind: "staples",
call: "867-5309",
fax: null
}; // error, call is not undefined
如果您确实需要支持此类对象,您可以将 NotAFunction
更改为更复杂并排除更少的非函数,但定义可能总会出错。由你决定 how far you want to go.
希望对您有所帮助。祝你好运!