繁体   English   中英

Object 的字符串和 () => typescript 中的字符串值

[英]Object of string and () => string values in typescript

我正在构建一个电报机器人
我想将所有消息存储为常量
我有一个消息模式,看起来像

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

它的实现是

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

我不能只将值设置为这个常量中的函数
我怎样才能重写架构以正确使用它?
我试着设置

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

但是每次我使用这个值时我都需要检查 object 值是否可调用

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

const断言satisfies运算符一起使用:

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

游乐场链接

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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