prgrmr
prgrmr

Reputation: 850

Typescript default function parameter

I am a super newbie to Typescript so sorry for a dumb question...

I want to write a function that takes arguments like below

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

}

GetAllFunctions() is something that returns an array and need to be the default for functionList but I could also do something like

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

What would be the correct way to do that

Upvotes: 0

Views: 240

Answers (3)

derbenoo
derbenoo

Reputation: 333

I believe this is the function signature you are looking for:

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

Upvotes: 0

JJWesterkamp
JJWesterkamp

Reputation: 7916

You placed the default value expression where the type annotation for functionList should be:

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

The : says "Here's the type for functionList". The = says "this is the default value for functionList".

You can also have only a default value (no type annotation), like this

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

... or only a type annotation (no default value), like this:

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

In any case, the meaning of : vs. = in the function signature remains the same.

Upvotes: 1

Krzysztof Grzybek
Krzysztof Grzybek

Reputation: 9416

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

}

Upvotes: 1

Related Questions