Używam biblioteki mssql, w której jest to interface
:
export interface IRecordSet<T> extends Array<T> {
columns: IColumnMetadata;
toTable(name?: string): Table;
}
Mam funkcję, która pobiera dane z bazy danych i zwraca tablicę IRecordSet<T>
tak , że jest to tablica tablic, które zawierają uniwersalny typ <T>
. Wygląda to tak:
[[{}, {}, ...], [{}, {}, ...], ...]
import { IRecordSet } from 'mssql'
type Data<T> = Array<IRecordSet<T>>
async function getData (sql: string): Promise<Data<any>> {
// connect to db, run sql
return []
}
Teraz potrzebuję funkcji, która powoduje getData()
i chciałbym wprowadzić rzeczywiste dane zwrócone, podając ogólny typ w IRecordSet<T>
.
Wiem, że to nie działa, ale to jest to, co mam teraz:
interface BookData {
name: string
author: string
}
interface CarData {
make: string
model: string
}
type BooksAndCars = Data<[BookData, CarData]>
async function getBooksAndCars (): Promise<void> {
const myData: BooksAndCars = await getData(`
SELECT name, author FROM Books;
SELECT make, model FROM Cars;
`)
const firstBook: BookData = myData[0][0]
const cars: CarData[] = myData[1]
// ...
}
Maszynopisu tekst mówi:
Type '[BookData, CarData]' is not assignable to type 'BookData'.
Type 'IRecordSet<[BookData, CarData]>' is not assignable to type 'CarData[]'.
Rozumiem te błędy, ale nie wiem, jak wpisać myData
, firstBook
& cars
zmienne, które także używają określone interfejsy (BookData
& CarData
).
Co powinno type BooksAndCars = Data<[BookData, CarData]>
być...?