【发布时间】:2018-12-04 16:10:33
【问题描述】:
我正在将一个简单的 JavaScript 节点模块和使用它的服务器代码迁移到 TypeScript,但是以某种方式发生了一些非常奇怪的事情......
我在下面使用了 Promise 链接语法:
api.Promise1().then(resultOfPromise1 =>
resultOfPromise1.isGood() ?
api.Promise2() :
Promise.reject({some:"errorInfo"})
).then(resultOfPromise2 => {
resultOfPromise2.doSomeThing();
}).catch(e => {
// Handle exception.
});
而 tsconfig.json 如下:
{
"compilerOptions": {
"lib": [
"es2015","es2016.array.include","es2017.string","es2015.promise"
]
}
}
使用上面的代码,tsc 给了我一个奇怪的错误,声称 resultOfPromise2 可以是“从不”类型:
error TS2339: Property 'doSomeThing' does not exist on type 'never'.
但即使出现此错误,编译后的 .js 也能正常运行。
这可能是 tsc 问题还是我丢失了什么?
更新这是代码的简化版本,编译时没有任何错误:
class SqlResult{
result: string;
}
function doSqlQuery(query: string): Promise<SqlResult>{
return new Promise((res, rej) => {
setTimeout(() => {
if (Math.random() > 0.5) {
res({ result: "123" });
} else {
rej(new Error("SQL "));
}
}, 20);
});
}
class Api{
Promise1():Promise<string>{
return doSqlQuery("").then(result => Promise.resolve(result.result))
}
Promise2():Promise<string>{
return doSqlQuery("").then(result => Promise.resolve(result.result))
}
}
var api = new Api();
api.Promise1().then(resultOfPromise1 =>
resultOfPromise1 == "QOO" ?
api.Promise2() :
Promise.reject({ some: "errorInfo" })
).then(resultOfPromise2 => {
console.log(resultOfPromise2);
}).catch(e => {
console.error(e);
});
我会花一些时间将完整的代码放到 Github 上,并切断机密信息和逻辑。
【问题讨论】:
-
api.Promise2()的定义是什么? -
api.Promise2() 也返回一个新的 Promise。
-
我在 api 模块中写了一个函数 doSqlQuery(string):Promise 并且 api.Promise1() 和 api.Promise2() 都包装了 doSqlQuery()。这些信息有帮助吗?
-
不是真的,目前还不清楚
Promise2()响应的样子。如果您可以在typescriptlang.org/play/index.html 上重现错误,那就容易多了 -
看起来可能是分支问题:resultOfPromise1.isGood() ? api.Promise2() : Promise.reject({some:"errorInfo"}) 如果您拒绝承诺,您是否有带有“doSomething”的结果对象
标签: javascript typescript es6-promise tsc