typescript - Vue3 与强类型 Axios 请求

标签 typescript vue.js axios vuejs3

我正在尝试了解 Vue3、TypeScript 和 Axios 的一些“类型安全”基础知识。

这是非常简单的东西,我觉得我好像错过了一些明显的东西!

我创建了一个Book界面:

Book.ts

interface Book {
  id: string;
  userId: string;
  title: string;
  content: string;
}

export default Book;

我还创建了一个简单的服务来获取一些 JSON,例如

  {
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
    "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
  },

(注意:JSON 具有 body 而不是接口(interface)上定义的 content)

DataService.ts

import axios, { AxiosResponse } from "axios";
import Book from "@/interfaces/Book";

class DataService {
  async FetchBooks(): Promise<Book[]> {
    let response: Book[] = [
      { id: "1", userId: "someone", title: "A title", content: "Some content" }
    ];
    try {
      const val = await axios.get<Book[]>(
        `https://jsonplaceholder.typicode.com/posts`
      );

      if (val.data && val.status === 200) {
        response = val.data;
      }
    } catch (error) {
      console.log(error);
    }

    return response;
  }
}

export default new DataService();

我的第一个问题是,当 Book 界面上不存在“body”时,为什么我的服务响应值仍然包含“body”?我希望当我将 Book 类型传递给 axios get 请求时,它会被丢弃。

我的第二个问题是,为什么我可以引用下面的 {{ book.body }},而我再次将响应作为 Book 处理>body 未在界面上定义?

Book.vue

<template>
  <div v-for="book in books" :key="book.id">
    <div class="mb-2">
      {{ book.body }}
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";
import DataService from "@/services/DataService";

// eslint-disable-next-line no-unused-vars
import Book from "@/interfaces/Book";

export default defineComponent({
  async setup() {
    let books: Book[] = [];

    await DataService.FetchBooks().then(data => (books = data));

    return { books };
  }
});
</script>

最佳答案

Why does my response value from the service still contain "body" when it does not exist on the Book interface?

因为在 TypeScript 中,interfaces只是定义实体“契约(Contract)”的一种方式。

也就是说,一个对象可以拥有比合约中定义的属性更多的属性,但编译器仅检查至少所需的属性是否存在并与所需的类型匹配。在某些情况下,TypeScript 并不那么宽松。 Learn more .

I was hoping it would get dropped somewhere along the line as I am passing the type Book to the axios get request.

所以它不会,除非您用它重新定义各个响应项(body 属性)并省略或重命名为 content——然后​​且只有这样——才会契约(Contract)功能处于最佳状态。例如:

const val = await axios
  .get<Array<Book & { body: string }>>(
    `https://jsonplaceholder.typicode.com/posts`
  )
  .then(res => res.data.map(
    ({ body, ...props }) => Object.assign({ content: body }, props)
  ));

为了避免类型断言困惑,我建议添加一个额外的 DTO原始 Book 对象 - 包含“原始”body 属性的交集类型。例如:

interface IBook {
  id: string;
  userId: string;
  title: string;
  content: string;
}

interface IBookRaw extends Omit<IBook, 'content'> {
  body: string;
}

添加该接口(interface)后,让我们借助实现此接口(interface)的来改进之前的数据映射,例如:

class Book implements IBook {
  id: string;
  userId: string;
  title: string;
  content: string;

  constructor({ id, userId, title, body }: IBookRaw) {
    this.id = id;
    this.userId = userId;
    this.title = title;
    this.content = body;
  }
}

const val = await axios
  .get<IBookRaw[]>(
    `https://jsonplaceholder.typicode.com/posts`
  )
  .then(res =>
    res.data.map(item => new Book(item))
  );

Why am I allowed to reference {{ book.body }} below, when again I am handling the response as a Book and body is not defined on the interface?

谈到模板插值,如果您使用 Vetur,则需要启用 vetur.experimental.templateInterpolationService 才能获得 linting 提示的好处。启用后,如果不首先修复模板上的“缺少属性”错误(这又是重命名 Prop 或省略它),您应该无法进行编译。

否则(没有 Vetur 的模板插值服务),将不会进行类型检查,当然最终会评估为 undefined

关于typescript - Vue3 与强类型 Axios 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64897859/

相关文章:

javascript - 将查询参数附加到 GET 请求?

javascript - 错误: getaddrinfo ENOTFOUND 3128 when post data using Axios in node js

angular - 如何在 Angular2\Typescript 中将字符串转换为日期?

在界面中使用枚举的 typescript

typescript 异步/等待无法确定正确的返回类型

javascript - Vue 屏幕定期刷新,安全完成

axios - 如何从 Axios 获取响应时间

javascript - 在 Angular 1.5 中使用 Typescript

javascript - 在 Laravel 中使用 Vue

javascript - Nuxt JS 中的基本身份验证