繁体   English   中英

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

[英]How to design interface shared by two classes that only one property type is different?

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

interface A {
    title: string
    catalogue: string
}

数据库实体类需要目录作为对象,因为CatObj包含其他信息,例如ID,名称等。

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中创建新接口?

泛型怎么样? A接口将是

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

然后,AEntity将变为:

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

杰森会是

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

如果您只有有限数量的外键,那么Andrei的答案是简单而直接的方法。

另一种方法是在Tyescript 2.8中使用条件类型(在撰写本文时尚未发布,但将在Match 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
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM