打字稿默认功能参数

时间:2020-03-04 20:13:33

标签: javascript typescript

我是Typescript的超级新手,很抱歉遇到一个愚蠢的问题...

我想编写一个函数,其参数如下所示

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

}

GetAllFunctions()是返回数组的东西,需要为functionList的默认值,但我也可以做类似的事情

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

正确的方法是什么

3 个答案:

答案 0 :(得分:1)

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

}

答案 1 :(得分:1)

您将默认值表达式放在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    
};

在任何情况下,函数签名中:=的含义都相同。

答案 2 :(得分:0)

我相信这是您要查找的功能签名:

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