TypeScript:需要两个解构参数之一

问题描述 投票:0回答:1

[创建需要设置两个可能的属性之一的接口时,类型并集非常有用:

enum Plans { bronze, silver, gold }
type Plan = keyof typeof Plans;

interface CreateSubscriptionBase {
  /** User's id */
  uid: string;
  /** Plan id */
  planName: Plan;
}

interface CreateSubscriptionPaymentMethod extends CreateSubscriptionBase {
  /** Payment Method id */
  paymentMethod: string;
}

interface CreateSubscriptionSource extends CreateSubscriptionBase {
  /** Source id */
  source: string;
}

export type CreateSubscriptionParams =
    CreateSubscriptionPaymentMethod
  | CreateSubscriptionSource

const sParams = {
  uid: 'foo',
  planName: 'bronze',
  source: 'source',
} as CreateSubscriptionParams

const pParams = {
  uid: 'foo',
  planName: 'bronze',
  paymentMethod: 'paymentMethod',
} as CreateSubscriptionParams

但是,当使用该接口对功能参数进行解构时,突然之间出现了麻烦:

function createSubscription({ uid, planName, paymentMethod, source }: CreateSubscriptionParams) {
  return 'hi'
}
example.ts:36:46 - error TS2339: Property 'paymentMethod' does not exist on type 'CreateSubscriptionParams'.

36   { uid, planName, paymentMethod, source }: CreateSubscriptionParams,
                      ~~~~~~~~~~~~~

example.ts:36:61 - error TS2339: Property 'source' does not exist on type 'CreateSubscriptionParams'.

36   { uid, planName, paymentMethod, source }: CreateSubscriptionParams,
                                     ~~~~~~

我们如何做到这一点?

typescript optional-parameters destructuring required-field
1个回答
0
投票
export interface CreateSubscriptionParams extends CreateSubscriptionPaymentMethod, CreateSubscriptionSource { }

编译器错误消失:

Playgound
热门问题
推荐问题
最新问题