Although I am still relatively new to Typescript, I find myself grappling with a particular issue that has been perplexing me. I am unsure why the following code snippet triggers a compilation error:
// An example without Promises (does not compile)
function getAnObject(): Object {
return { value: 'Hello' };
};
function doSomethingWithAString(input: String) {
console.log(input);
}
const result = getAnObject();
// error TS2345: Argument of type 'Object' is not assignable to parameter of type 'String'
doSomethingWithAString(result);
On the other hand, this similar piece of code does not raise any errors:
// A similar example with Promises (compiles)
function getAnObjectAsync(): Promise<Object> {
return Promise.resolve({ value: 'Hello' });
};
getAnObjectAsync().then(function (result: String) {
// Throws a runtime exception
console.log(result.toUpperCase());
});
This discrepancy leaves me wondering why TypeScript tolerates the fact that the onfulfilled
function within the .then
handler in the Promise scenario expects an input of type result: Object
.
- Have I misunderstood something?
- Could there be a key detail about this example that eludes me?