VSCode中如何实现fetch JSON数据后的属性自动补全?
让VSCode对fetch返回的JSON数据提供属性自动补全
默认情况下,await fetch('./data.json')返回的是Response对象,不是解析后的JSON数据,所以直接输入a.只会提示Response类的内置方法(比如json()、text()),不会显示property1和property2。要实现目标自动补全,需要先解析JSON数据,再通过类型提示让VSCode识别数据结构,具体有两种常用方案:
方案一:纯JavaScript项目用JSDoc类型注解
通过JSDoc定义对应data.json结构的类型,再给解析后的变量标注类型:
/** * @typedef {Object} DataJson * @property {string} property1 * @property {string} property2 */ // 先获取Response对象,再解析为JSON const response = await fetch('./data.json'); /** @type {DataJson} */ const data = await response.json(); // 此时输入data.会自动补全property1、property2 console.log(data.property1);
方案二:TypeScript项目用接口定义
直接定义对应数据结构的接口,再通过类型断言指定解析后的数据类型:
interface DataJson { property1: string; property2: string; } const response = await fetch('./data.json'); const data = await response.json() as DataJson; // 输入data.即可自动补全目标属性
内容的提问来源于stack exchange,提问作者Arunachalam
相关产品推荐
相关产品推荐

