#Item is in array type with class method guard?

8 messages · Page 1 of 1 (latest)

tawny iron
#

On line 36 im calling a method that i want to be a typeguard to ensure that the call on line 37 wont be undefined. is this even possible?

vital umbraBOT
#
Th3FalleN#9999

Preview:```ts
import type Stripe from "stripe"

export default class SubscriptionManager {
#subscription

constructor(args: Stripe.Subscription) {
this.#subscription = args
}

// get subscription line items
getLineItems() {
return this.#subscription.items!.data
}

getLineItemByPriceId($priceId: Stripe
...```

tawny iron
#

Item is in array type with class method guard?

grim stirrup
#

you can type guard the this type, but with the setup you have i think you'd also have to conditionalize the return type of some of your other methods to be aware of whether there is a price ID or not (might not be unreasonable to do so via subclassing, but would require a lot of boilerplate in any case)

it'd be simpler to rewrite buildUpdateRequestPayload to avoid the need for narrowing this:

vital umbraBOT
#
mkantor#7432

Preview:```ts
...
id
)
}

buildUpdateRequestPayload(
prices: Stripe.Price["id"][],
qty: number
) {
return {
subscriptionId: this.#subscription.id,
quantity: qty,
items: prices.map(priceId => {
const id =
this.getLineItemByPriceId(priceId)?.id
if (id !== undefined) {
return {id}
} else {
return {priceId}
}
}),
}
}
...```

snow meadow
#
 items: prices.map(priceID => {
        const lineItem = this.getLineItemByPriceId(priceID)
        if (!!lineItem) {
          return { id: lineItem.id };
        }
        return { priceId: priceID };
      }),
#

you could do this, right?

#

or if you wanna do it but be fancy about it