Home > database >  What is the use of destructuring in a generic declaration?
What is the use of destructuring in a generic declaration?

Time:04-29

Destructuring might be the wrong term...

Found this in the codebase I'm working in. It's perplexing.

await apolloClient
    .query<{ Workorder: Workorder }>({
      query: WORKORDER_QUERY,
      variables: { uuid: id },
    })

I don't see the point of { Workorder: Workorder }. What is happening here? What is the value of that vs .query<Workorder>?

Workorder is an interface with about 30 properties.

CodePudding user response:

It's not destructuring. It just means that the type argument being passed is an object with a Workorder property, and that the value for that property is a Workorder.

For example, given:

type Workorder = { order: boolean };
declare function fn<T>(): T;

const result = fn<Workorder>();

where the type parameter is the same type that's returned, the result is of type:

{
  order: boolean
}

Whereas if you do

const result = fn<{ Workorder: Workorder }>();

the result is now of the type:

{
  Workorder: {
    order: boolean
  }
}

Not that .query does the same thing, but that'll give you an idea of what the difference is. Doing <{ Workorder: Workorder }> just wraps the Workorder in an object and passes it as a type parameter.

  • Related