簡體   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