Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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'){
   ...
}

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading