我是 Typescript 的 super 新手,很抱歉问了一个愚蠢的问题......
我想编写一个接受如下参数的函数
export const AutoComplete = async (
str: string,
functionList?: GetAllFunctions()
) => {
}
GetAllFunctions()
是返回一个数组的东西,需要成为 functionList
的默认值,但我也可以做类似的事情
自动完成('foo', ['foo', 'bar'...])
正确的做法是什么
最佳答案
您将默认值表达式放置在 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
};
无论如何,函数签名中 :
与 =
的含义保持不变。
关于javascript - Typescript 默认函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60534008/