Код: Выделить всё
interface FetchDataProps {
route: string;
tableFormattedData?: ({ data }: { data: unknown }) => object[];
}
export default async function fetchData({
route,
tableFormattedData,
}: FetchDataProps) {
const response = await api.get(route);
const { data, page, total_records } = response.data;
const currentPage = page - 1;
const newPaginationData = {
data: tableFormattedData
? tableFormattedData({
data,
})
: data,
page: currentPage,
totalCount: total_records,
};
return { newPaginationData, currentPage };
}
< /code>
Это то, что я делал, чтобы достичь того, что я хочу: < /p>
interface ResponseDataProps {
data: T[];
page: number;
total_records: number;
}
type FetchDataProps = {
route: string;
tableFormattedData?: (args: { data: DataProps[] }) => FormattedDataProps[];
};
type FetchDataReturn =
FormattedDataProps extends undefined
? {
newPaginationData: {
data: DataProps[];
page: number;
totalCount: number;
};
currentPage: number;
}
: {
newPaginationData: {
data: FormattedDataProps[];
page: number;
totalCount: number;
};
currentPage: number;
};
export async function fetchData({
route,
tableFormattedData,
}: FetchDataProps) {
const response = await api.get(route);
const { data, page, total_records } = response.data;
const currentPage = page - 1;
const newPaginationData = {
data: tableFormattedData
? tableFormattedData({
data,
})
: data,
page: currentPage,
totalCount: total_records,
};
return {
newPaginationData,
currentPage,
} as FetchDataReturn;
}
Код: Выделить всё
interface FormattedProps {
id: string;
name: string;
}
interface DataProps {
id: string;
}
export async function test() {
const test2 = await fetchData({
route: 'test2',
tableFormattedData: () => {}
});
test2.newPaginationData.data[0].name;
}
< /code>
Если я попытаюсь получить доступ к имени, оно не будет найдено. Переменная Test3
Код: Выделить всё
export async function test() {
const test3 = await fetchData({
route: 'test3',
tableFormattedData: () => {}
});
if ('name' in test3.newPaginationData.data[0]){
test3.newPaginationData.data[0].name
}
}
Подробнее здесь: https://stackoverflow.com/questions/793 ... meter-in-t