I am developing a typescript project. Currently, my challenge is the ts(2322) error.
Here is my code.
import {
BASE_URL,
AIRTABLE_BASE_ID,
AIRTABLE_TABLE_STUDENT,
AIRTABLE_TABLE_CLASSES,
API_KEY,
} from './../../config/config';
// A mock function to mimic making an async request for data
export function fetchCount(amount = 1) {
return new Promise<{ data: number }>((resolve) =>
setTimeout(() => resolve({ data: amount }), 500)
);
}
// Result object
interface Result {
records: [
{
id: string;
createdTime: string;
fields: {
Name?: string;
Students?: [string];
Classes?: [string];
};
}
];
}
// Class info object
interface ClassInfo {
Name: string | undefined;
Students: [string | undefined];
}
// fetch airtable data by url
const fetchData = (endpoint: string) => {
return fetch(endpoint, {
headers: new Headers({
'Content-Type': 'application/json',
Authorization: `Bearer ${API_KEY}`,
}),
}).then((res) => res.json());
};
// fetch classes record ids by student name
const fetchClassesByStudent = (name = '') => {
const endpoint = `${BASE_URL}${AIRTABLE_BASE_ID}${AIRTABLE_TABLE_STUDENT}?filterByFormula=Name="${name}"&fields[]=Classes`;
return fetchData(endpoint);
};
// fetch classes names and students ids from classes record ids
const fetchClassesInfo = (classids: [string]) => {
const endpoint = `${BASE_URL}${AIRTABLE_BASE_ID}${AIRTABLE_TABLE_CLASSES}?filterByFormula=OR(${classids
.map((val) => `RECORD_ID() = "${val}"`)
.join(', ')})`;
return fetchData(endpoint);
};
// fetch students names from students ids
const fetchStudentsNames = (studentids: [string]) => {
const endpoint = `${BASE_URL}${AIRTABLE_BASE_ID}${AIRTABLE_TABLE_STUDENT}?filterByFormula=OR(${studentids
.map((val) => `RECORD_ID() = "${val}"`)
.join(', ')})&fields[]=Name`;
return fetchData(endpoint);
};
// fetch class and its students list
export function fetchList(name = '') {
const classList: [ClassInfo?] = [];
fetchClassesByStudent(name).then((res: Result) => {
const classids = res.records?.[0].fields.Classes;
if (classids) {
fetchClassesInfo(classids).then((res: Result) => {
res.records.map((value) => {
if (value.fields.Students && value.fields.Name) {
fetchStudentsNames(value.fields.Students).then((res: Result) => {
const eachClass: ClassInfo = {
Name: value.fields.Name,
Students: res.records.map((value) => value.fields.Name),
};
});
}
});
});
}
});
}
If I change the ClassInfo interface to
interface ClassInfo {
Name: string | undefined;
Students: (string | undefined)[];
}
Then no error. I just want to know what is difference between (T)[] and [T]. Also want to know if the array could have no value, and what I should put in the interface.
[T]denote an array containing exactly one element of typeT?