Reputation:
I'm working on a Demo API Wrapper for Roblox, yet I've encountered an issue. Basically, what I'm trying to do is send a request but then return all the data as an API wrapper would do. Yet, I don't know how I'd type this certain property. This because, the object can change depending on the type of action I sent with the request.
As you can see here. The description object is empty.
[{
...
"actionType": "string",
"description": {},
"created": "2021-04-19T21:21:48.513Z"
}]
But when I send a request, I can either get this or even more.
"description": {
"Targetld": "2434302765",
"OldRoIeSetId": "33456000",
"NewRoIeSetId": "21608541",
"Targetname": "t_ru9",
"OldRoIeSetName": "______________"
"NewRoIeSetName": "folk"
}
So with this, How would I have a TypeScript Interface handle all of this without using the Unknown keyword?
Upvotes: 0
Views: 181
Reputation: 1884
For the example provided, you can use the Record
interface.
Record<string, Record<string, any>>
represents an object with unknown keys, where any one of those keys may contain another object of unknown key-value pairs.
You can change the types in the inner Record, if you can be more specific. For instance, in your given description example, it appears as though Record<string, string>
may be sufficient.
So a real world example, using Observables and Subscription would look similar to:
somePostApiCall(requestBody: Record<string, any> = {}): Observable<Record<string, any>> {
return this.http.post<Record<string, any>>('someurl', requestBody);
}
In your use case, you simply need to specify an object type. So if you have a variable:
basicExample: Record<string, any>; // This will accept a key value object with no specified key names
Upvotes: 0
Reputation: 5188
How about a generic object type?
interface SomeInterface {
...
description: { [key: string]: string | number }
}
const myObj: SomeInterface = {}
console.log(myObj.description.TargetId); //works
*But you will not have any autocomplete
Upvotes: 1