簡體   English   中英

Typescript 默認函數參數

[英]Typescript default function parameter

我是 Typescript 的超級新手,很抱歉問一個愚蠢的問題......

我想編寫一個帶有如下參數的函數

export const AutoComplete = async (
    str: string,
    functionList?: GetAllFunctions()
) => {

}

GetAllFunctions()是返回一個數組的東西,需要是functionList的默認值,但我也可以做類似的事情

AutoComplete ('foo', ['foo', 'bar'...])

這樣做的正確方法是什么

export const AutoComplete = async (
  str: string,
  functionList = GetAllFunctions()
) => {

}

您將默認值表達式放置在functionList的類型注釋應該是:

export const AutoComplete = async (str: string, functionList: string[] = GetAllFunctions()) => {
//                                              ^^^^^^^^^^^^  ^^^^^^^^   ^^^^^^^^^^^^^^^^^
//                                              arg name      type       default value
};

:表示“這是 functionList 的類型”。 =表示“這是 functionList 的默認值”。

你也可以只有一個默認值(沒有類型注釋),像這樣

export const AutoComplete = async (str: string, functionList = GetAllFunctions()) => {
//                                              ^^^^^^^^^^^^   ^^^^^^^^^^^^^^^^^
//                                              arg name       default value
};

...或者只有一個類型注釋(沒有默認值),像這樣:

export const AutoComplete = async (str: string, functionList: string[]) => {
//                                              ^^^^^^^^^^^^  ^^^^^^^^
//                                              arg name      type    
};

在任何情況下,函數簽名中: vs. =的含義保持不變。

我相信這是您正在尋找的函數簽名:

export const AutoComplete = async (str: string, functionList: string[] = GetAllFunctions()) => {};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM