After transitioning my Vue project to TypeScript, I encountered a situation that requires some management.
To handle paginated tables in my application, I developed a Table
mixin that manages pagination for my collection of records:
@Component
export default class Table<T> extends Vue {
records: T[] = []
page: number = 0
length: number = 20
get total () {
return this.records.length
}
get visibleRecords(): T[] {
return this.records.slice(this.page*this.length, (this.page+1)*this.length)
}
public changePage (newPage: number) {
this.page = newPage
}
}
Each component that renders the table extends the mixin, populates the records
property, and displays the result of the visibleRecords
computed property. Here's a basic example:
export default class Sampletable extends Mixins(Table) {
records: RecordType[] = [ .... my data array ... ]
}
<template>
<table>
<tr v-for="record in visibleRecords">
....
</tr>
</table>
</template>
While this setup works, calling 'visibleRecords' loses the knowledge of the data type (RecordType
in the example). What I aim for is TypeScript to recognize that visibleRecords
(implemented in the mixin) returns the same data type as the records
property (which is overridden in the component implementing the mixin).
I attempted to implement the Table
mixin with a generic type (as shown in the previous code) but encountered an issue, as I couldn't define the generic type when extending the Mixin:
export default class Sampletable extends Mixins(Table<RecordType>)
This resulted in an error being thrown. Is there a solution to achieve this? Any suggestions?