【问题标题】:Extend multiple interface in TypeScript with OR condition使用 OR 条件扩展 TypeScript 中的多个接口
【发布时间】:2020-12-28 18:06:48
【问题描述】:

我有三个接口

inteface A {
    name: string
    id: number
    address: string
    details : object
}

   inteface B {
        name: string
        id: string
        address: string
        details : string
        age: number
    }



inteface C {
        name: string
        id: string
        address: object
        details : object
        age: number
        height: number
    }

是的,你注意到了,不同的接口可能有不同类型的公共字段 比如接口Aid: number,但Bid: string

现在我有了一个通用接口

interface Common {
   group: string
   class: string
}

现在我有一个函数,它接受参数 Object,它肯定有 interface Common 字段,但可能有接口 A、B 和 C 之一的字段

我想使用Common,它将扩展其中的任何一个接口ABC

function insert(params: Common){
   ....
}

       

现在我想使用泛型,但我没有做我想做的事, 那么有人可以告诉我如何将它与泛型一起使用并获得我想要的,如果它可以通过泛型来完成,

如果不建议我另一种方法。

【问题讨论】:

    标签: node.js typescript generics interface typescript-generics


    【解决方案1】:

    你可以这样做:

    
    type ABC = A | B | C
    
    function insert(params: Common & ABC): {
      ...
    }
    

    【讨论】:

    • 好的。但是,这是我的例子:export interface A { type: string; svc:字符串; } 导出接口 B { id: string; } 导出类型 AB = A |乙; func(config: AB) { if (config.type) { ... } 这给我带来了一个 TS 错误:TS2339: 属性 'type' 在类型 'AB' 上不存在。类型“B”上不存在属性“类型”。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-09
    • 2020-04-09
    • 2016-07-06
    • 1970-01-01
    • 1970-01-01
    • 2017-03-04
    相关资源
    最近更新 更多