美文网首页
求一个TypeScript中interface的定义

求一个TypeScript中interface的定义

作者: asins | 来源:发表于2019-11-28 23:55 被阅读0次

    我想对现有浏览器端ajax请求做一次封闭,后端接口定义使用Object定义的形式出现,在最终项目中使用时统一转换为fetch的方法。

    // import qs from 'qs';
    
    interface RequestOptions {
        url: string;
        type: 'post' | 'get' | 'POST' | 'GET';
    }
    interface ApiList {
        [key: string]: RequestOptions;
    }
    const apiList: ApiList = {
        getData: {
            url: '/api/get',
            type: 'post',
        },
        getUser: {
            url: '/api/user',
            type: 'POST',
        },
    };
    
    function createFetch(config: RequestOptions) {
        return function (params: any): Promise<any> {
            let url: string = config.url;
            // if (config.type.toLowerCase() === 'get') {
            //     config.url += (config.url.includes('?') ? '&' : '?') + qs.stringify(params);
            // }
    
            return fetch(url, {
                body: JSON.stringify(params),
                headers: {
                    'content-type': 'application/json'
                },
                method: config.type.toUpperCase(),
            }).then(response => response.json());
        }
    }
    
    class Api {
        public api;
        constructor() {
            for (const key in apiList) {
                this.api[key] = createFetch(apiList[key]);
            }
        }
    }
    
    const api = new Api();
    api.api.getData({ a: 22 });
    

    以上api最终是一个方法集合对象,如:

    api = {
      getData: function(params){},
      getuser: function(params){},
    }
    

    但api的TS类型定义我一直没能正确的写出,不知有哪位高手能指点下。

    相关文章

      网友评论

          本文标题:求一个TypeScript中interface的定义

          本文链接:https://www.haomeiwen.com/subject/sktwwctx.html