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

Time:01-14

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

CodePudding user response:

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

  • Related