Confusion Over Promise Type Error
How did the TypeScript compiler generate the error message displaying
Type Promise <string|number> ...
in the following scenario?
Type 'Promise<string | number>' is not assignable to type 'Promise<number>'. Type 'string | number' is not assignable to type 'number'. Type 'string' is not assignable to type 'number'.
The code snippet that triggers this error message is shown below:
const promise: Promise<number> = Promise.resolve(100).then(n => n.toString());
Expectation vs Reality
I anticipated that
Promise.resolve(100).then(n => n.toString())
would result in a Promise<string>
.
When trying to assign it to const promise: Promise<number>
, I expected TypeScript to flag a mismatch between Promise<string>
and Promise<number>
However, TypeScript perplexingly introduces a string|number
union and raises an issue with Promise<string|number>
not being compatible with Promise<number>