【问题标题】:React.js and Typescript return type of a fetch API Response?React.js 和 Typescript 返回获取 API 响应的类型?
【发布时间】:2021-12-25 13:04:48
【问题描述】:

是否有可能在运行时检查 fetch API 请求的响应类型?据我所知,Response 总是有吗?如果它与类型不匹配或接受数据,是否可以抛出错误?这是我的代码:

import React, { useEffect, useState } from 'react';
import logo from './logo.svg';
import './App.css';

type Test = {
  name: string;
  age?: number;
}

interface TodoData {
  id: number,
  userId: number,
  title: string,
  completed: boolean,
}

type JSONResponse = () => {
    ok?: boolean,
    status: 200 | number,
    json: () => Promise<TodoData> | Promise<TodoData>[];
}

const App: React.FC<Test> = ({name, age}) => {
  const [todos, setTodos] = useState(null);

  useEffect(() => {
    const fetchData: any = async () => {
      let todos: Response = await fetch('https://jsonplaceholder.typicode.com/todos');
      console.log(todos);
      let todoData: JSONResponse = await todos.json();
      console.log({todoData});
    }
    fetchData();  
  },[])

  return (
    <div className="App">
      <p>Hello {name} your age is {age? age: "not given here."}</p>
    </div>
  );
}

export default App;

【问题讨论】:

  • 你可以使用 axios 代替 fetch。 Axios自带'很简单的方式来输入body、response...
  • 如果你想坚持使用 fetch,可以使用 Joi 为响应定义一个模式。然后,您可以针对响应数据在架构上调用 validate()

标签: reactjs typescript async-await httpresponse fetch-api


【解决方案1】:

在 Node.js 或您的浏览器可以执行 TypeScript 之前,必须将其编译为 JavaScript。 Javascript 无法理解 TypeScript 中的类型注解,因此必须在此步骤中将其删除。

因为您的 API 数据仅在运行时可用,而 TypeScript 类型在运行时不可用,所以您无法使用 TypeScript 对响应数据进行类型检查。

但是,您可以教 TypeScript 您希望接收的数据的结构,它会阻止您以非法方式访问数据。

如果您必须在运行时验证响应,JOI 之类的东西是个好主意。 (感谢Robert Hartshorn 的建议)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-12
    • 2019-04-16
    • 2020-08-08
    • 1970-01-01
    • 2020-08-10
    • 1970-01-01
    相关资源
    最近更新 更多