這是官方文件,可以看到 chat_id 可以用 Integer 或 String
然後這是我寫的lib
class tgbot3 {
token: string
api_url: string
constructor(token: string) {
this.token = token
this.api_url = `https://api.telegram.org/bot${this.token}/`
}
public sendMessage(
{
chat_id = '',
text = '',
parse_mode = '',
disable_web_page_preview = false,
disable_notification = false,
reply_to_message_id = 0,
reply_markup = '',
} = {}
) {
if (chat_id === '') this.miss_parameter("chat_id")
if (text === '') this.miss_parameter("chat_id")
let start_payload = {
"method": "sendMessage",
'chat_id': String(chat_id),
'text': String(text),
'parse_mode': parse_mode,
'disable_web_page_preview': disable_web_page_preview,
'disable_notification': disable_notification,
'reply_to_message_id': reply_to_message_id,
'reply_markup': reply_markup,
}
return this.start(start_payload)
}
private miss_parameter(parameter: string) {
throw new Error(`Missing ${parameter}`)
}
private start(payload: any) {
let data = {
"method": "post",
"payload": payload
}
// @ts-ignore
return UrlFetchApp.fetch(this.api_url, data);
}
}
然後 ts 就噴錯給我看,說不能指定整數給 "string|undefined" 的 chat_id
"string|undefined"中的 string 是因為我指定預設值為 ''
然後 undefined 是因為後面的 "{}" (如下圖)因為沒指定東西所產生的
想先請問這樣理解有錯嗎?
之後我查找一堆資料後,自己修改成這樣(ts應許),希望能來指定type
public sendMessage(
{
chat_id ,
text,
parse_mode,
disable_web_page_preview,
disable_notification,
reply_to_message_id,
reply_markup,
}: {
chat_id:string|number|undefined,
text:string|undefined,
parse_mode:string|undefined,
disable_web_page_preview:Boolean|undefined,
disable_notification:Boolean|undefined,
reply_to_message_id:string|number|undefined,
reply_markup:any|undefined,
}={
chat_id : '',
text:'',
parse_mode:'',
disable_web_page_preview:false,
disable_notification:false,
reply_to_message_id:'',
reply_markup:'',
}
) {
if (chat_id === '') this.miss_parameter("chat_id")
if (text === '') this.miss_parameter("text")
let start_payload = {
"method": "sendMessage",
'chat_id': String(chat_id),
'text': String(text),
'parse_mode': parse_mode,
'disable_web_page_preview': disable_web_page_preview,
'disable_notification': disable_notification,
'reply_to_message_id': reply_to_message_id,
'reply_markup': reply_markup,
}
return this.start(start_payload)
}
然後就可以用了
可是卻變成要求要輸入全部的參數才能用(如下圖拿掉 reply_markup 後)
這樣的話就沒有預設值的意義了
謝謝各位m(_ _)m
想先請問這樣理解有錯嗎?
沒有
可以用可選引數的方式
chat_id?: string|number|undefined,
另外解構賦值給定預設值應該是這樣
{
chat_id = '',
text = '',
parse_mode = '',
disable_web_page_preview = false,
disable_notification = false,
reply_to_message_id = '',
reply_markup = '',
}: {
chat_id?:string|number|undefined,
text?:string|undefined,
parse_mode?:string|undefined,
disable_web_page_preview?:Boolean|undefined,
disable_notification?:Boolean|undefined,
reply_to_message_id?:string|number|undefined,
reply_markup?:any|undefined,
} = {}