【问题标题】:Typescript interface are not overloading / merging subsequent interface fieldsTypescript 接口未重载/合并后续接口字段
【发布时间】: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


【解决方案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
 */

Demo1

你需要做的是创建一个联合类型。就像@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

Demo2

【讨论】:

  • 当我这样做时,我在猫鼬模型功能上得到Type 'StoreConfig' does not satisfy the constraint 'Document'.。这是我在另一个文件中的代码model<StoreConfig>(Model.StoreConfiguration, schema)
  • @tbhaxor 抱歉,我不知道这里的猫鼬上下文
  • 另外,当我为每个接口(这又是一个接口)添加新字段 metadata 时,我只看到公共字段(仅在所有三个主要 StoreConfig 中具有相同类型和名称的字段)接口)参见这个 loom 视频,例如,loom.com/share/2df3da5a9afc4462838bf14d66daceb9
  • 分享您的 STORE_CONFIG 课程。你需要做一些小的重构,因为 STORE CONFIG 实例应该已经定义了所有属性
  • 我创建了一个要点here
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-09-27
  • 2016-08-05
  • 2021-12-12
  • 2016-12-26
  • 2019-08-17
  • 2017-07-01
  • 1970-01-01
相关资源
最近更新 更多