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'

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();
}
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.
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!
Use the parameter?: type syntax to make a parameter optional. Use the expression typeof(parameter) !== 'undefined' to check if the parameter has been initialized.
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.
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 = '')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With