Home > other >  Is there a way in TS to autocomplete all the properties of unknow object structure returned from a P
Is there a way in TS to autocomplete all the properties of unknow object structure returned from a P

Time:10-15

I am new in TS world and I was wondering if it's possible to make a request to an API end point which returns an object with a structure which I don't know.

Can TS help me with the properties in advance with autocompletion?

CodePudding user response:

If you don't know what the response object structure will be, you can use unknown as a basis and afterwards check the type of the result.

const result = (await response.json()) as unknown;

You will need a list of all the possible types you expect the response to be if you want autocompletion to work, because TS needs some definition of what the object could be.

Let's say I expect one of two types:

interface Person {
  id: number
  name: string;
  age: number;
}

and

interface Message {
  id: number
  text: string;
  sender: string;
  receiver: string;
}

You can use type guards to check what the actual result is. First you have to create your custom type guards, like this:

const isPerson = (person: Person | unknown): person is Person =>
  !!(person as Person)?.id || !!(person as Person)?.name || !!(person as Person)?.age;

and

const isMessage = (message: Message | unknown): message is Message =>
  !!(message as Message)?.id || !!(message as Message)?.text || !!(message as Message)?.sender || !!(message as Message)?.receiver;

Now you can use these type guards to know if the result is one of these defined types:

if (!!isPerson(result)) {
  // result is of type Person and autocompletion will work with properties of type Person
} else if (!!isMessage(result)) {
  // result is of type Message and autocompletion will work with properties of type Message
} else {
  // result is of type unknown and further checks will need to done
}

CodePudding user response:

Yes there is one long journey is if your API ecosystem had GRAPHQL implementation by that you know what is coming from the server.

check this for reference

  • Related