7

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();
}
Shaun Luttin
  • 133,272
  • 81
  • 405
  • 467
FunkyFabe
  • 149
  • 2
  • 8

3 Answers3

5

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 = '')
Aleksey L.
  • 35,047
  • 10
  • 74
  • 84
3

Why do you get this error?

First, the type of query is not string but is the union type of string | undefined. That is because optional parameters have a union type of T | undefined.

Second, assigning a variable of type T | undefined to a variable of type T does not compile when TypeScript 2.0 uses strict null checks. From the docs:

...whereas T and T | undefined are considered synonymous in regular type checking mode (because undefined is considered a subtype of any T), they are different types in strict type checking mode...

VS Code with strict null checks does report the problem.

How do you fix this error?

One option is to set strictNullChecks to false in your tsconfig.json file.

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

Community
  • 1
  • 1
Shaun Luttin
  • 133,272
  • 81
  • 405
  • 467
  • 2
    You wrote that one option is to set strictNullChecks to false. I wonder if there are other options? I find it surprising that the TS compiler would keep emitting this error even for a parameter that is marked as optional and that the only solution is to disable a check that would otherwise be useful. – AbVog Jan 01 '18 at 00:42
0

The short answer is that Typescript wants you to put a type check before the function call, to eliminate "undefined" from the list of possible types. Eg:

if (typeof myVar !== 'undefined') {
    myFunction(myVar);
}

Or, because 'undefined' is falsy, you could use the double-bang boolean-casting trick:

if (!!myVar) { myFunction(myVar); }
meetar
  • 7,443
  • 8
  • 42
  • 73