I have built a function that sends an axios Request. I use typescript and don't want to use any as the return data types of the function and the axios request itself.
The problem is, however, that the object that comes back contains the params id, which in turn is an object. Honestly, I have never seen such an object. I do not even know what kind of an object that is. Maybe it is some basic stuff which I never heard about. It is pretty difficult to make a good google search regarding that.
I want to create an typescript interface out of it. I do not even have a good idea to start.
Would appreciate any help
this is a small part of the return object:
{
data{
'12345': { // params.id --> causing my poblem
address: {
...,
}}}
}
Thats my function
async function getData (): Promise<IReturnData[]> {
const {data} = await axios.get<IReturnData>(`....${id}`) // in our case 12345
return Object.entries(data.data)[0];
}
How should I build IReturnData ?
export interface IReturnData {
data {
string: { adress: Adress......
}}}
or
export interface IReturnData {
data {
"1234 but that will change on every request": {
adress: Adress......
}}}
I think the best you can do is using Mapped Types.
But it's not perfect, see the example below, or this playground...
interface MyModel {
[key: string]: Address;
}
const goodExample: MyModel = {
"12345": {
country: "Germany"
}
}
const badExample: MyModel = { // Sadly this also works, but I don't think there is a way to limit it to one key
"12345": {
country: "Germany"
},
"23456": {
country: "Germany"
}
}