I have created a function with multiple overloads as follows:
function convertToString(value: string | undefined): string | undefined;
function convertToString(value: string): string ;
function convertToString(value: string | undefined): string | undefined {
return value?.toString();
}
My goal is to have the return type as string
when passing a value of type string
, and as string | undefined
when passing a value of type string | undefined
.
However, I am encountering a compilation error when making a simple call:
const x: string = convertToString('abc');
TS2322: Type 'string | undefined' is not assignable to type 'string'. Type 'undefined' is not assignable to type 'string'.
I would appreciate any assistance in properly defining the function, thank you!