Typescript: optional function arguments cause problems in the 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 an argument query(see screenshot). I really don't understand this error because I defined the type as string. So why am I getting this error?

message: string "Type argument" | undefined 'is not assigned to a parameter of type' string '. The type 'undefined' is not assigned to the type 'string'

Screenshot 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();
}
+4
source share
2 answers

getRequestURL query string, fetchPut string | undefined ( ).

query getRequestURL :

getRequestURL(requestURL: string, query?: string)

:

getRequestURL(requestURL: string, query: string = '')
+2

?

-, query string, string | undefined. , T | undefined.

-, T | undefined T , TypeScript 2.0 . :

... T T | undefined ( undefined T), ...

VS Code with strict zero checks reports a problem.

?

- strictNullChecks false tsconfig.json.

VS Code without strict null checks does not report the problem.

+2

Source: https://habr.com/ru/post/1670195/


All Articles