繁体   English   中英

在函数签名中将对象值用于TypeScript键入

[英]Using object values for TypeScript typings in function signature

我们在代码库的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' refers to a value, but is being used as a type here.ts(2749)

有什么方法可以将Templates对象重用为一种类型,还是我需要将其重构为Enum或有人有什么好的建议? 提前致谢!

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

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

您可以使用String Enums,解决方案是:

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

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

这是有关枚举的一些信息 ,以备您查看。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM