VSCode扩展开发TypeScript提示ProviderResult无push属性如何解决?
问题原因
- 类型声明错误:你将
result的类型声明为vscode.ProviderResult<vscode.Location[]>,该类型本身是联合类型,包含Location[] | Thenable<Location[] | null | undefined>,TypeScript无法确定运行时result一定是数组类型,因此判定push方法可能不存在。 - 异步逻辑错误:
vscode.workspace.findFiles和fs.readFile都是异步执行的API,你当前的写法会在异步回调执行前就返回result,最终返回的永远是空数组,即使解决类型问题也无法拿到预期结果。
解决方法
首先将函数改写为异步函数,用async/await处理异步逻辑,同时直接将result声明为vscode.Location[]类型,避免联合类型的判断问题,另外建议使用fs.promises版本的API适配async/await写法,避免回调嵌套。
修正后的代码示例:
async getTest(label: string): Promise<vscode.Location[]> { const result: vscode.Location[] = []; // 等待findFiles返回结果 const files = await vscode.workspace.findFiles('*.m'); for (const file of files) { const path = file.fsPath; // 等待文件读取完成 const content = await fs.promises.readFile(path, 'utf8'); result.push(new vscode.Location(vscode.Uri.file(path), new vscode.Position(1, 1))); } return result; }
如果你的注册的Provider要求返回ProviderResult类型也无需额外调整,异步函数返回的Promise本身就符合ProviderResult的类型要求。
内容的提问来源于stack exchange,提问作者Jens
相关产品推荐
相关产品推荐

