I have a type like this: ```ts export type WithRelationship< IModel extends object, IRelationship extends object, IRelationshipKeys extends keyof IRelationship = keyof IRelationship
= IModel & { readonly [P in IRelationshipKeys as
${Lowercase< string & P >}Relationship
]: IRelationship[P]; };
// IModel example interface IForklift { id: string; status: number; }
// IRelationship example interface IForkliftRelationship { status: IForkliftStatus; } ```
IModel
is implemented by a class (I'm using Objection.JS). With Objection.JS, I can specify relationships with a static property and can call on it later to get related data:
```ts
export class Forklift implements IForklift {
id: string;
status: number;
static relationMappings = () => { statusRelationship: { relation: Model.HasOneRelation, modelClass: ForkliftStatus, join: { from: "forklift.id", to: "forklift_status.forklift_id" } } } }
// Query results type when relationship not called { id: string; status: number; }
// Query results type when relationship called { id: string; status: number; statusRelationship: ForkliftStatus } ```
When I query the database and typecast it to WithRelationship<IForklift, IForkliftRelationship
, it throws an error: Property 'statusRelationship' is missing in type 'Forklift' but required in type '{ readonly statusRelationship: IForkliftStatus; }'
, which makes sense. My question is, is there some way I can have the class have any property ending with Relationship
, without manually specifying each relationship as a class property?
Subreddit
Post Details
- Posted
- 2 years ago
- Reddit URL
- View post on reddit.com
- External URL
- reddit.com/r/typescript/...