我试着用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,而不是接口上定义的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“?当我将Book类型传递给axios请求时,我希望它会在行的某个地方被删除。
我的第二个问题是,为什么允许我在下面引用{{ 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>发布于 2020-11-18 19:20:49
为什么当响应值在Book接口上不存在时,服务的响应值仍然包含"body“?
因为在TypeScript中,接口只是定义实体“契约”的一种方式。
也就是说,对象可以具有比契约上定义的属性更多的属性,但是编译器只检查至少需要的属性是否存在并匹配所需的类型。有些情况下,TypeScript并不那么宽容。了解更多。
当我将
Book类型传递给axios请求时,我希望它会在行的某个地方被删除。
所以它不会,除非您用它重新定义单独的响应项( body属性),省略或重命名为content-then,只有这样,契约才能发挥最佳的作用。例如:
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对象--其中包括"raw“body属性的一个交集类型。例如:
interface IBook {
id: string;
userId: string;
title: string;
content: string;
}
interface IBookRaw extends Omit<IBook, 'content'> {
body: string;
}添加了该接口后,让我们借助实现此接口的class来改进以前的数据映射,例如:
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))
);为什么允许我在下面引用
{{ book.body }},当我再次处理响应时,在接口上没有定义Book和body?
谈到模板内插,如果您使用Vetur,您需要启用vetur.experimental.templateInterpolationService来获得linting提示的好处。一旦启用,您就不应该能够编译,除非首先修复模板上的“缺失属性”错误(再次重命名或者省略它)。
否则(没有Vetur的模板内插服务),就不会进行类型检查,当然,它最终将评估为undefined。
https://stackoverflow.com/questions/64897859
复制相似问题