简体   繁体   English

TypeScript - 使用可选属性定义数据 model

[英]TypeScript - defining the data model with optional properties

I'm pretty new to TypeScript.我对 TypeScript 很陌生。 I would like to have a Table, that can have a group or rows property defined.我想要一个可以定义组行属性的表。

Already added the interfaces for the data model:已经为数据 model 添加了接口:


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)

but when it comes to the table component, I'm not sure how to specify that I would like to have TableWithRows in one case, and TableWithGroups in another.但是当涉及到表格组件时,我不确定如何指定我希望在一种情况下使用 TableWithRows,而在另一种情况下使用 TableWithGroups。

I get an error when trying to spread the values from the data object, which is totally fine because TableModel might not have one of them.尝试从数据 object 传播值时出现错误,这完全没问题,因为 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'

}

How should I specify that I want explicitly one of the table types?我应该如何明确指定我想要其中一种表类型? Is this achievable by making TableModel generic?这可以通过使 TableModel 通用来实现吗?

What's the best practice for having one of the values required?拥有所需值之一的最佳实践是什么?

You could do it like this - with a union:你可以这样做 - 使用工会:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM