Skip to content

Commit

Permalink
Add QueryResultOptionalPopulated helper type
Browse files Browse the repository at this point in the history
  • Loading branch information
jgeurts committed Jan 8, 2022
1 parent 015a49d commit 428cbfd
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 1 deletion.
8 changes: 7 additions & 1 deletion src/types/EntityPrimitiveOrId.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
import type { Entity } from '../Entity';

export type EntityPrimitiveOrId<T extends Entity> = Extract<NonNullable<T>, Entity> extends Entity ? Exclude<NonNullable<T>, Entity> | Pick<T, 'id'> : T;
export type EntityPrimitiveOrId<T> = T extends []
? T extends (infer U)[]
? EntityPrimitiveOrId<U>[]
: T // Unable to determine array type, so return original
: Extract<NonNullable<T>, Entity> extends undefined
? T
: Exclude<NonNullable<T>, Entity> | Pick<Extract<NonNullable<T>, Entity>, 'id'>;
15 changes: 15 additions & 0 deletions src/types/QueryResultOptionalPopulated.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import type { Entity } from '../Entity';

import type { EntityPrimitiveOrId } from './EntityPrimitiveOrId';
import type { QueryResult } from './QueryResult';

/**
* Allows a QueryResult type with specific properties optionally populated. If the property is populated, only the id property is needed
*/
export type QueryResultOptionalPopulated<T extends Entity, K extends keyof T> = Omit<QueryResult<T>, K> & {
[P in K]-?: T[P] extends []
? undefined extends T[P] // If property is not an array
? EntityPrimitiveOrId<T[P]> | null // If the property is originally optional, include null as a possible value type
: EntityPrimitiveOrId<T[P]> // Otherwise, use the TPropertyType
: EntityPrimitiveOrId<T[P]>; // Otherwise return an array of items
};
1 change: 1 addition & 0 deletions src/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,4 @@ export * from './PickFunctions';
export * from './Populated';
export * from './QueryResult';
export * from './QueryResultPopulated';
export * from './QueryResultOptionalPopulated';

0 comments on commit 428cbfd

Please sign in to comment.