【发布时间】:2016-12-21 16:49:44
【问题描述】:
我仍在学习 Typescript,所以也许我只是从根本上遗漏了一些东西,但我不明白为什么以下代码会引发编译错误:
// 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);
但下面的代码没有:
// 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());
});
为什么 TypeScript 没有抱怨 Promise 示例中 .then 的 onfulfilled 函数会收到 result: Object?
- 我做错了吗?
- 我对这个例子有什么不明白的地方吗?
【问题讨论】:
标签: javascript typescript promise