如何设计只有一个属性类型不同的两个类共享的接口?

时间:2018-02-24 14:27:31

标签: typescript oop

假设我有两个班级(或更多)。一个作为数据库实体,一个作为json约束。因为数据库实体将属性设置为外键,因此属性是对象。但在json的情况下,属性只是一个字符串类型。

interface A {
    title: string
    catalogue: string
}

数据库实体类需要将目录作为Object,因为CatObj包含其他信息,如id,name等。

class AEntity implements A {
    public title: string
    public catalogue: CatObj
}

json格式

const aJson: A = {
    title: 'hello',
    catalogue: 'programming'
}

其余属性是相同的。

如何在TypeScript中设计接口(或其他方式)来进行此类约束?除了将目录类型设为

之外还有其他方法吗?
catalogue: string | CatObj

由于CatObj仅在数据库部分中可见,因此A是一个使用后端和前端部分的全局接口。是否有方法允许选择接口的某些属性以在TypeScript中创建新接口?

2 个答案:

答案 0 :(得分:3)

仿制药怎么样? A接口将是

bool

然后AEntity将成为:

interface A <TCat> {
      title: string
      catalogue: TCat
}

而Json将是

class AEntity implements A<CatObj> {
      public title: string
      public catalogue: CatObj
}

答案 1 :(得分:2)

如果你只有有限数量的外键,安德烈的回答是一个简单而直接的方法。

另一种方法是在Tyescript 2.8中使用条件类型(在编写本文时尚未发布,但将在2018年匹配版中发布,您可以通过运行npm install -g typescript@next获得)。您可以使用指向其他接口的外键字段定义接口,然后使用条件类型将接口转换为仅包含字符串的版本:

interface Base {
    id: string // should contain something, any type maching the structure of Base will be converted to string
}

interface A extends Base{
    title: string
    prop: number
    catalogue: CatObj
    otherFk: OtherFk;
}

interface CatObj extends Base {
    title: string
}

interface OtherFk extends Base {
    title: string
}

// JsonData will convert all fields of a type derived from Base to string 
type JsonData<T> = { [P in keyof T] : T[P] extends Base ? string : T[P] }

// will be a type { title: string;prop: number;catalogue: string;otherFk: string;id: string;}
type JsonA = JsonData<A> 


class AEntity implements A {
    public id: string
    public prop: number
    public title: string
    public catalogue: CatObjEntity // field implemented by a field of an entity type
    public otherFk: OtherFk // Or a field can be implemented using the interface
}

class CatObjEntity implements CatObj {
    public id: string
    public title: string
}