0

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?

2
  • Hey, welcome to Stackoverflow. Please create codeblocks for source code in your question not images. This will help users to get a better overview of your code. Commented Apr 20, 2021 at 12:21
  • @JanneckLange, Sure will. Thanks. Commented Apr 21, 2021 at 5:31

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

This is probably what I'm looking for but could you provide more info or a link on how I would learn more about something like that ( [key: string]....)?
@tru9 Here you go Indexable Types
0

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

Comments