Currently working on some Typescript challenges and encountered a scenario involving a union type.
In this example, the function getIstanbulPostalCode
is declared to return either a string or a number:
function getIstanbulPostalCode(): string | number {
return 34116;
}
let postalCode: number = getIstanbulPostalCode();
postalCode;
The outcome is a type error stating that type 'string | number' cannot be assigned to type 'number'.
The variable postalCode
calls getIstanbulPostalCode
which returns a number instead of the expected types.
Since the function requires a valid string
or number
, this results in a type error where 'string' cannot be converted to 'number'.
function istanbul(): number { return 34116; }
let istanbul2: string | number = istanbul();
istanbul2;
The output here is 34116
.
I am puzzled by the second instance with the istanbul
function where it correctly handles a number as output.
However, when we have istanbul2
defined as potentially either a string
or number
, there are no type errors. This raises a question about the discrepancy between using parameters with a union type within a function versus assigning a variable like istanbul2
.
Your insights would be greatly appreciated.