TypeScript-定义具有可选属性的数据模型



我对TypeScript还很陌生。我想要一个表,它可以定义一个组行属性。

已经为数据模型添加了接口:


type GroupModel = {
id: UUID
name: string
rows: RowModel[]
}
interface Table {
readonly header: HeaderModel[]
readonly pageIndex?: number
readonly pageSize?: number
}
interface TableWithGroups {
readonly groups: GroupModel[]
}
interface TableWithRows {
readonly rows: RowModel[]
}

export type TableModel = Table & (TableWithRows | TableWithGroups)

但是当涉及到表组件时,我不知道如何指定在一种情况下我希望使用TableWithRows,在另一种情况中使用TableWithGroups。

我在尝试从数据对象中扩展值时遇到了一个错误,这完全没问题,因为TableModel可能没有其中一个。

const Table = ({ data }: Props) => {
const { rows, groups } = data
// Property 'rows' does not exist on type 'TableModel'
// Property 'groups' does not exist on type 'TableModel'
}

我应该如何指定我想要显式的表类型之一?这可以通过使TableModel通用来实现吗?

拥有所需价值之一的最佳实践是什么?

您可以这样做-使用联合:

interface TableWithOption {
optionType: GroupModel[] | RowModel[]
}

最新更新