Interface

  1. type Method = 'get' | 'post'
  2. interface EasyFetchRequestConfig {
  3. url: string
  4. method?: Method
  5. data?: any
  6. params?: any
  7. headers?: any
  8. responseType?: XMLHttpRequestResponseType
  9. timeout?: number
  10. }
  11. function test(config: EasyFetchRequestConfig): void {
  12. console.log(config.url)
  13. }
  14. test({ url: 'test', num: 2 }) // 会报错,因为num没有定义
  15. test({}) // 报错,url属于必传
  16. test({ url: 'test' }) // 编译通过

混合工厂

  1. interface EasyFetch {
  2. getURL(url: string): string
  3. }
  4. /** 混合工厂接口 */
  5. interface EasyFetchInstance extends EasyFetch {
  6. (start: number): string
  7. }
  8. function createInstance(): EasyFetchInstance {
  9. const instance = function(start: number): string {
  10. return 'test'
  11. }
  12. instance.getURL = function (url: string): string { return url };
  13. return instance
  14. }
  15. const easyFetch = createInstance()
  16. easyFetch(2)
  17. easyFetch.getURL('mmp.xxx')

Type

类型别名

  1. type Method = 'get' | 'post' // 只能2选1
  2. interface EasyFetchResponse {
  3. status: string
  4. }
  5. type EasyFetchPromise = Promise<EasyFetchResponse>
  6. function xhr(): EasyFetchPromise {
  7. return Promise.resolve({status: 'success'})
  8. }
  9. xhr().then(status => {
  10. console.log(status)
  11. })