0

我知道打字稿中的接口允许我们合并不同的类型。当我尝试这样做时,我在编译脚本时遇到了错误。

这是我的错误界面

export interface StoreConfig extends Document, TimeStamps {
  type: 'webhook'
  metadata: {
    endpoint: string
    method: HttpMethod
    secret: string
    event: string | string[]
  }
}

export interface StoreConfig extends Document, TimeStamps {
  type: 'buylink'
  metadata: {
    prodId: string
    key: string
    expire: Date
  }
}

export interface StoreConfig extends Document, TimeStamps {
  type: 'paymentmethod'
  metadata: {
    apiKey: string
    mode: string
    whsecret: string
  }
}

我在转换 ts 脚本时收到此错误

Subsequent property declarations must have the same type.  Property 'type' must be of type '"webhook"', but here has type '"buylink"'.

PS:我看到许多库(例如:nodemailer、inquirer)正在加载基于某些标志或条件的类型。

4

1 回答 1

1
/**
 * Simplified example
 */

export interface StoreConfig extends Document {
    type: 'webhook'

}

export interface StoreConfig extends Document {
    type: 'buylink'

}

export interface StoreConfig extends Document {
    type: 'paymentmethod'
}

/**
 * This is how it works
 * 1) 
 */

export interface A {
    type: 'buylink'

}

export interface A {
    payload: number
}

type O = keyof A // type | payload

/**
 * Because you can't do smth like that
 */

type CustomType = 'buylink' & 'webhook' // never

/**
 * Above type is never because it is irrepresentable
 * Please treat merging as & operator on high level
 */

演示1

您需要做的是创建一个联合类型。就像@ritaj 在他的评论中写道:

export interface StoreConfig1 extends Document {
    type: 'webhook'

}

export interface StoreConfig2 extends Document {
    type: 'buylink'

}

export interface StoreConfig3 extends Document {
    type: 'paymentmethod'
}

type StoreConfig = StoreConfig1 | StoreConfig2 | StoreConfig3

演示2

于 2020-12-16T09:13:54.000 回答