我正在尝试了解 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 aBook
andbody
is not defined on the interface?
谈到模板插值,如果您使用 Vetur,则需要启用 vetur.experimental.templateInterpolationService
才能获得 linting 提示的好处。启用后,如果不首先修复模板上的“缺少属性”错误(这又是重命名 Prop 或省略它),您应该无法进行编译。
否则(没有 Vetur 的模板插值服务),将不会进行类型检查,当然最终会评估为 undefined
。
关于typescript - Vue3 与强类型 Axios 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64897859/