在下面的场景中声明Book接口的“正确”方式是什么,请记住,我们知道两种情况下book对象的确切结构。假设有一个Book接口:
export interface Book {
id: string;
title: string;
year: number;
authorId: string;
pages: number;
language: string;
}还有一个Author接口,它有一个book属性,由“部分”book对象组成的数组:
export interface Author {
id: string;
firstName: string;
lastName: string;
// How this book object should be declared?
books: Array<{ id: string; title: string, year: number }>;
}发布于 2019-06-01 04:02:01
如果"partial“指的是使Book上的任何属性成为可选的,那么可以使用typescript的导出帮助器Partial
export interface Author {
...
books: Partial<Book>[]
}如果您所说的“部分”意味着它只包含Book的一些属性,并且这些属性应该保持其原始类型,那么您可以使用typescript导出的助手类型Pick
export interface Author {
...
books: Pick<Book, "id" | "title" | "year">[]
}发布于 2019-06-01 04:02:52
这真的取决于你想要完成什么。
您可以使用Partial关键字books: Partial<Book>[];,或者创建另一个接口来包含{ id: string; title: string, year: number }接口的图书。
https://stackoverflow.com/questions/56400809
复制相似问题