gpt4 book ai didi

typescript - 如何在 TypeScript 中声明仅包含对象而不包含函数的类型

转载 作者:行者123 更新时间:2023-12-03 21:22:08 27 4
gpt4 key购买 nike

是否可以在 TypeScript 中以某种方式定义类型,使其仅包含对象而不包含函数?

例子:

type T = { [name: string]: any } // How to modify this to only accepts objects???

const t: T = () => {} // <- This should not work after modification

谢谢你的帮助。

最佳答案

没有完美的方法来引用像“不是函数的对象”这样的类型,因为这需要 true subtraction types ,而这在 TypeScript 中不存在(至少从 3.1 开始)。

一种简单的解决方法是查看 Function interface并描述绝对不是 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

好的。

这是一种变通方法而不是简单的解决方案的原因是某些非函数可能同时具有 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 - 如何在 TypeScript 中声明仅包含对象而不包含函数的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52692606/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com