I am currently developing a type-safe JSON:API specification parser for handling API responses that can either contain a single object or an array of objects ().
For example, when making a request like GET /article
:
{
data: {
type: 'article',
id: article_id_1,
attributes: {
name: article_1,
price: price_1
}
}
}
or GET /articles
:
{
data: [{
type: 'article',
id: article_id_1,
attributes: {
name: article_1,
price: price_1
},
}, {
type: 'article',
id: article_id_2,
attributes: {
name: article_2,
price: price_2
},
}]
}
To ensure type safety in my function, I aim to create a generic function called parseData<T>
where T
defines the expected data structure. For instance:
interface TArticle {
id: string,
type: string,
name: string,
price: number,
}
The current implementation is as follows:
function parseData<T>(data: Data<T>): T | T[]
Although functional, it still allows the return type to be ambiguous between T and T[]. Thus, when calling the function:
const result = parseData<TArticle>(articleData);
It becomes uncertain whether the result is TArticle or TArticle[]. While casting the result based on prior knowledge is possible, a more robust TypeScript solution would be preferable.