I am currently utilizing typescript for the backend application and find myself struggling with what seems to be a simple issue. Despite searching through articles on Google, I still lack confidence in my understanding.
Picture this scenario: when receiving a response from the API endpoint, the typical schema appears as follows:
some_array: [
{ key: value },
{ key: value },
{ key: string || number || nested object }
]
number_key: 12,
string_key: 'string'
As evident, the structure is not entirely static; the some_array
field - which is usually an array upon success - may contain varied types of data within objects.
There is also a possibility of encountering errors or unexpected outcomes.
TypeScript offers safety through typed declarations, but the uncertainty arises when dealing with potential responses of varying types from the endpoint.
For instance, what sets apart:
api as any
//inside async function
const api: any = await fetch('/endpoint');
//I must manually verify the response types to prevent incorrect typings
if (!api|| !Array.isArray(api.some_array) || !api.some_array.length) return
for (const document of api.some_array) {
//perform any function or action
}
from api as predefined interface
interface ApiResp = {
some_array: { [key: string]: any }[]
number_key: number
string_key: string
}
//inside async function
const api: ApiResp = await fetch('/endpoint');
// should I solely check for the existence of api, given that its interface is predetermined?
for (const document of api.some_array) {
//perform any function or action
}
In the second approach, does it mean that I no longer need to perform type checks like
if (!api|| !Array.isArray(api.some_array) || !api.some_array.length) return
, and instead, all incorrect response types will throw an error upon receipt (in the const api
) after compilation to JavaScript code? Could I then simply check for the existence of api
only, using something like if (api) ....
?
Or, if the actual API response does not match the defined interface
, would it try to access the for of
loop and trigger an error there? (considering scenarios where the endpoint responds with errors such as: {error: 404}
without the expected field like some_array
?)