【发布时间】:2020-12-16 17:22:10
【问题描述】:
我知道 typescript 中的接口允许我们合并不同的类型。当我尝试这样做时,我在编译脚本时遇到了错误。
这是我的错误界面
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)都在加载基于某些标志或条件的类型。
【问题讨论】:
-
以不同的方式命名接口,然后
export type StoreConfig = Interface1 | Interface2 | Interface3; -
这是预期行为。 接口的非函数成员应该是唯一的。如果它们不是唯一的,则它们必须属于同一类型。如果两个接口都声明了同名但类型不同的非函数成员,编译器将发出错误。 typescriptlang.org/docs/handbook/…
标签: typescript mongoose mongoose-models