简体   繁体   中英

Using object values for TypeScript typings in function signature

We've defined some enum values in a const in our codebase, like this:

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

(Example is shortened intentionally, but does in fact contain almost 100 entries for our different HTML templates for messages.).

We want to use these names as typings for a function like

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

But of course we get Templates' refers to a value, but is being used as a type here.ts(2749)

Is there any way to reuse the Templates object as a type, or do I need to refactor it to be an Enum or does anyone have any good suggestions? Thanks in advance!

I've tried searching for similar topics, by searching for "reuse objects as types in TypeScript" but it does in fact seem I need to do something advanced here, or just refactor.

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

You can use String Enums, the solution would be:

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

You may use the Enum as type, and also get the string.

Here is some info about enum, in case you want to take a look.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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