Search code examples
typescriptvisual-studio-codeoptional-arguments

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();
}

Solution

  • 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 = '')