簡體   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