Shopify / shopify-app-js

MIT License
216 stars 86 forks source link

question: product types from rest api #763

Open Z3rio opened 4 months ago

Z3rio commented 4 months ago

Hello, quick question. How are product types and such imported from the Rest API?

I've tried to import them from the RestResources object, as that's the only types being exported, but they do not seem to be useable, unless I'm missing something.

example:

import { RestResources } from "@shopify/shopify-api/rest/admin/2024-01";
import { shopify } from './utils/shopify' // setup of shopify API obj

function test(prod: RestResources["Product"] | null): void {
  console.log("hello world");
}

(async () => {
  // act like session & productId is defined
  const prod = await shopify.rest.Product.find({
    session: session,
    id: productId
  })

  test(prod);
})

This would result in the following error, as the types do not match:

- error TS2345: Argument of type 'Product' is not assignable to parameter of type 'typeof Product'.
  Type 'Product' is missing the following properties from type 'typeof Product': prototype, apiVersion, hasOne, hasMany, and 16 more.
Z3rio commented 4 months ago

Seems like we could technically use this:

type ShopifyProduct = NonNullable<Awaited<ReturnType<typeof shopify["rest"]["Product"]["find"]>>>

But that just seems dumb & overcomplicated in my opinion, surely there should be some exported types for this, no?

paulomarg commented 4 months ago

Hi, thanks for raising this. I think this is an interesting issue. A simpler way to get test() to work would be to declare it like this:

function test(prod: InstanceType<RestResources['Product']> | null): void {
  // ...
}

By using the InstanceType utility, you can define the prod parameter as being an instance of that class. While still a little more complicated than it has to be, this might unblock you.

I'll keep this open so we can evaluate exporting the classes as types, but there are other things that are going to be higher priority!

github-actions[bot] commented 3 weeks ago

We're labeling this issue as stale because there hasn't been any activity on it for 60 days. While the issue will stay open and we hope to resolve it, this helps us prioritize community requests.

You can add a comment to remove the label if it's still relevant, and we can re-evaluate it.