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



假设我有两个类(或更多(。一个作为数据库实体,一个作为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'
}

其余属性是相同的。

如何在打字稿中设计一个接口(或其他方式(以制定这种约束?除了将目录类型作为

做出其他方式以外,还有其他方法
catalogue: string | CatObj

因为CatObj仅在数据库部分中可见,所以A是使用后端和前端部分使用的全局接口。是否有一种方法可以拾取接口的某些属性来在打字稿中制作新接口?

generics怎么样?A接口将是

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

然后,aentity将成为:

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

,JSON将是

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

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

另一种方法是在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
}

最新更新