简体   繁体   中英

TypeScript: Enforce that an interface only contains property-keys that are present in a specific class

I have the following class that is used as an entity for an object-relational-mapper:

@Entity("MyEntity")
export class MyEntity {
  @PrimaryGeneratedColumn()
  id!: number;

  @Column("varchar", { length: 2000 * 2 })
  data!: string;

  @CreateDateColumn()
  created!: Date;
}

Now for some reason, most of my code does not use this class. Instead, the code uses a "model"-interface that is a loose subset of this class:

export interface MyModel {
  id: number;
  data: string;
}

A problem with this approach is that the model-interfaces can get easily out-of-sync with the entity-classes. This leads to my question:

How can I statically enforce that all property-keys of MyModel are also present in MyEntity ?

I'm not sure If I got your question, but you can implement the interface and enforce those properties.

interface MyModel {
    id: number;
    data: string;
}

// This throws: Class 'MyEntity' incorrectly implements interface 'MyModel'.
class MyEntity implements MyModel {

}

// This works
class MyEntity implements MyModel {
    data: string;
    id: number;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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