简体   繁体   中英

Object of string and () => string values in typescript

i am building a telegram bot
i want to store all my messages as a constant
i have a message schema, which looks like

type MessagesSchema = {
    [K in keyof typeof MessagesEnum]: string
}

and it's implementation as

const Messages: MessagesSchema = {
    SOME_KEYS_FROM_ENUM = '123',
    ...
    FUNCTIONAL_VALUE: (a: number) => `The number is ${a}`
}

i can't just set values as functions in this constant
how can i rewrite schema to correctly use that?
i tried to set

type MessagesSchema = {
    [K in keyof typeof MessagesEnum]: string | ((...params: any) => string)
}

but then i need to check is object value callable every time i use this value

if(typeof Messages.FUNCTIONAL_VALUE === 'function'){
   ...
}

Use a const assertion with the satisfies operator:

const Messages = {
    SOME_KEYS_FROM_ENUM: '123',
    //...
    FUNCTIONAL_VALUE: (a: number) => `The number is ${a}`
} as const satisfies MessagesSchema

Messages.SOME_KEYS_FROM_ENUM
//       ^? "123"
Messages.FUNCTIONAL_VALUE(0) // Okay
//       ^? (a: number) => string

Playground Link

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