如何在 TypeScript 中使用 fetch

How to use fetch in TypeScript

我在 Typescript 中使用 window.fetch,但我无法将响应直接转换为我的自定义类型:

我正在通过将 Promise 结果转换为中间 'any' 变量来解决这个问题。

执行此操作的正确方法是什么?

import { Actor } from './models/actor';

fetch(`http://swapi.co/api/people/1/`)
      .then(res => res.json())
      .then(res => {
          // this is not allowed
          // let a:Actor = <Actor>res;

          // I use an intermediate variable a to get around this...
          let a:any = res; 
          let b:Actor = <Actor>a;
      })

如果你看一下 @types/node-fetch 你会看到正文定义

export class Body {
    bodyUsed: boolean;
    body: NodeJS.ReadableStream;
    json(): Promise<any>;
    json<T>(): Promise<T>;
    text(): Promise<string>;
    buffer(): Promise<Buffer>;
}

这意味着您可以使用泛型来实现您想要的。我没有测试这段代码,但它看起来像这样:

import { Actor } from './models/actor';

fetch(`http://swapi.co/api/people/1/`)
      .then(res => res.json<Actor>())
      .then(res => {
          let b:Actor = res;
      });

接下来是几个示例,从基本到在请求后添加转换 and/or 错误处理:

基本:

// Implementation code where T is the returned data shape
function api<T>(url: string): Promise<T> {
  return fetch(url)
    .then(response => {
      if (!response.ok) {
        throw new Error(response.statusText)
      }
      return response.json<T>()
    })

}

// Consumer
api<{ title: string; message: string }>('v1/posts/1')
  .then(({ title, message }) => {
    console.log(title, message)
  })
  .catch(error => {
    /* show error message */
  })

数据转换:

通常您可能需要在将数据传递给消费者之前对其进行一些调整,例如,展开顶级数据属性。这是直截了当的:

function api<T>(url: string): Promise<T> {
  return fetch(url)
    .then(response => {
      if (!response.ok) {
        throw new Error(response.statusText)
      }
      return response.json<{ data: T }>()
    })
    .then(data => { /* <-- data inferred as { data: T }*/
      return data.data
    })
}

// Consumer - consumer remains the same
api<{ title: string; message: string }>('v1/posts/1')
  .then(({ title, message }) => {
    console.log(title, message)
  })
  .catch(error => {
    /* show error message */
  })

错误处理:

我认为你不应该直接在这个服务中直接捕获错误,而是让它冒泡,但如果你需要,你可以执行以下操作:

function api<T>(url: string): Promise<T> {
  return fetch(url)
    .then(response => {
      if (!response.ok) {
        throw new Error(response.statusText)
      }
      return response.json<{ data: T }>()
    })
    .then(data => {
      return data.data
    })
    .catch((error: Error) => {
      externalErrorLogging.error(error) /* <-- made up logging service */
      throw error /* <-- rethrow the error so consumer can still catch it */
    })
}

// Consumer - consumer remains the same
api<{ title: string; message: string }>('v1/posts/1')
  .then(({ title, message }) => {
    console.log(title, message)
  })
  .catch(error => {
    /* show error message */
  })

编辑

自从前段时间写下这个答案以来,有一些变化。如评论中所述,response.json<T> 不再有效。不确定,找不到它被删除的位置。

对于以后的版本,您可以这样做:

// Standard variation
function api<T>(url: string): Promise<T> {
  return fetch(url)
    .then(response => {
      if (!response.ok) {
        throw new Error(response.statusText)
      }
      return response.json() as Promise<T>
    })
}


// For the "unwrapping" variation

function api<T>(url: string): Promise<T> {
  return fetch(url)
    .then(response => {
      if (!response.ok) {
        throw new Error(response.statusText)
      }
      return response.json() as Promise<{ data: T }>
    })
    .then(data => {
        return data.data
    })
}

实际上,在 typescript 的几乎任何地方,将值传递给具有指定类型的函数都可以按需要工作,只要传递的类型兼容。

话虽这么说,以下作品...

 fetch(`http://swapi.co/api/people/1/`)
      .then(res => res.json())
      .then((res: Actor) => {
          // res is now an Actor
      });

我想将我所有的 http 调用包装在一个可重用的 class 中 - 这意味着我需要一些方法让客户端以其所需的形式处理响应。为了支持这一点,我接受一个回调 lambda 作为我的包装器方法的参数。 lambda 声明接受任何类型,如下所示...

callBack: (response: any) => void

但在使用中,调用者可以传递指定所需 return 类型的 lambda。我像这样从上面修改了我的代码...

fetch(`http://swapi.co/api/people/1/`)
  .then(res => res.json())
  .then(res => {
      if (callback) {
        callback(res);    // Client receives the response as desired type.  
      }
  });

以便客户端可以通过回调调用它...

(response: IApigeeResponse) => {
    // Process response as an IApigeeResponse
}