Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: Optional function arguments cause problems in function body

I am new to TypeScript and have a little problem with an optional argument in a function. I got the following error in Visual Studio Code for the query argument (see screen shot). I really don't understand this error, because I defined the type as string. So why do I get this error?

message: 'Argument of type 'string | undefined' is not assignable to parameter of type 'string'. Type 'undefined' is not assignable to type 'string'

Screen shot error in VS Code

public async fetchPut<T>(requestURL: string, body: TBody, query?: string): Promise<T> {

    const finalRequestOption: IFetchOption = Object.assign({
        method: 'PUT',
        headers: this.headers
    }, { body });

    const response: Response = await this.httpClient.fetch(
            this.getRequestURL(requestURL, query), 
            finalRequestOption);

    return response.json();
}
like image 730
FunkyFabe Avatar asked Feb 19 '17 00:02

FunkyFabe


People also ask

Does TypeScript support optional parameter in function?

TypeScript provides a Optional parameters feature. By using Optional parameters featuers, we can declare some paramters in the function optional, so that client need not required to pass value to optional parameters.

How do you pass optional arguments in TypeScript?

Use a question mark to set an optional parameter in a function in TypeScript, e.g. function sum(a: number, b?: number) {} . If set to optional, the parameter can have a type of undefined or the specified type, because unspecified parameters get the value undefined . Copied!

How do you make a parameter in a function signature optional in TypeScript?

Use the parameter?: type syntax to make a parameter optional. Use the expression typeof(parameter) !== 'undefined' to check if the parameter has been initialized.

Why optional parameters are added in TypeScript?

Optional Parameters are parameters that can be specified, but are not required. This allows for functions that are more customizable, without requiring parameters that many users will not need.


Video Answer


1 Answers

getRequestURL function expects query to be a string, but fetchPut function defines query as string | undefined (optional parameter).

You can define query parameter of getRequestURL as optional as well:

getRequestURL(requestURL: string, query?: string)

Or provide default value for it:

getRequestURL(requestURL: string, query: string = '')
like image 135
Aleksey L. Avatar answered Sep 17 '22 12:09

Aleksey L.