TypeScript Promise链编译报错TS2345:类型不匹配问题求助
问题原因与解决办法
核心问题
你在then方法里直接传入了一个Promise实例,而**then要求的参数是回调函数**,这是类型不匹配导致的TS2345错误。
Promise.prototype.then()的正确用法是接收1-2个函数参数:第一个是前一个Promise成功时执行的回调(参数是前一个Promise的返回值),第二个是失败时的回调(可选)。你直接传new Promise(...),TypeScript会判定这个Promise实例不符合(value: void) => void | PromiseLike<void>的函数签名,所以报错。
修正后的代码
如果只是想在Promise链完成后打印消息,直接把第三个then的内容改成回调函数即可:
performInit(): Promise<void> { // 建议替换any为明确的void,因为最终没有返回值 console.log('performInit started'); const promise = this.getUserCredentials() .then(this.service.getMetaData.bind(this.service)) .then(() => { // 这里改成回调函数 console.log('performInit completed'); // 原代码打印内容疑似笔误,建议改为完成提示 }) .catch((error: unknown) => console.error(error)); // 用console.error打印错误更规范 return promise; }
补充说明
如果你的打印逻辑是异步操作(需要用Promise包裹),那也应该把它放在回调函数里返回:
.then(() => { return new Promise(resolve => { setTimeout(() => { console.log('performInit completed'); resolve(); }, 1000); }); })
另外,尽量避免用any作为Promise的返回类型,根据实际返回值定义类型会让代码更健壮。
内容的提问来源于stack exchange,提问作者Leos Literak
相关产品推荐
相关产品推荐

