gpt4 book ai didi

javascript - 在函数签名中使用 TypeScript 类型的对象值

转载 作者:行者123 更新时间:2023-12-02 23:46:54 25 4
gpt4 key购买 nike

我们在代码库的 const 中定义了一些枚举值,如下所示:

const Templates = {
NewMessageFromBot: 'new_message_from_bot,
NewMessageFromHuman: 'new_message_from_human',
NewUnreadNotification: 'new_unread_notification',
}

(示例被有意缩短,但实际上包含了我们不同的消息 HTML 模板的近 100 个条目。)。

我们希望使用这些名称作为函数的类型,例如

function getTemplateName(message: MessageDocument, templateName: Templates) { ... }

但是我们当然得到Templates'引用一个值,但在这里被用作类型。ts(2749)

有没有办法重用Templates对象作为类型,或者我是否需要将其重构为Enum或者有人有什么好的建议吗?提前致谢!

我尝试通过搜索“在 TypeScript 中将对象重用为类型”来搜索类似的主题,但事实上我似乎需要在这里做一些高级的事情,或者只是重构。

function getTemplateName(message: MessageDocument, templateName: Templates) { ... }

最佳答案

您可以使用字符串枚举,解决方案是:

enum Templates = {
NewMessageFromBot = 'new_message_from_bot,
NewMessageFromHuman = 'new_message_from_human',
NewUnreadNotification = 'new_unread_notification',
}

您可以使用 Enum 作为类型,并获取字符串。

这里有一些 info关于枚举,如果您想看一下。

关于javascript - 在函数签名中使用 TypeScript 类型的对象值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55818658/

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