在JavaScript规范或IntelliJ平台中,有没有办法定义从AJAX调用中收到的对象的结构?
示例:
$.ajax({
type: 'POST',
url: 'https://myapi.domain.com/apitest',
success: function(payload) {
let username = payload.userNameField; //unresolved variable "userNameField"
}
});
在上面的示例中,WebStorm报告payload.userNameField
是一个"未解决的变量"。
我有什么方法可以定义对象,以便它不会显示错误,也可能是自动填充?
答案 0 :(得分:0)
感谢@chazsolo指导我使用WebDorm本身支持的JSDoc的“Custom complex type”,这个解决方案很有用:
$.ajax({
type: 'POST',
url: 'https://myapi.domain.com/apitest',
success: processResponse
});
/**
* Definition of the object returned by the api call
* @typedef {Object} processResponse~payload
* @property {string} userNameField - Username returned by API
*/
/**
* Definition of function that handles the response
* @class
* @param {...processResponse~payload} payload - the data returned by the call
*/
function processResponse(payload) {
let username = payload.userNameField; //no errors now and autocomplete works!
};