Created
October 23, 2020 14:50
-
-
Save AlexAegis/701fd9edde34a7175118ff00d9373837 to your computer and use it in GitHub Desktop.
Convert relative models to foreign keys
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export interface Model { | |
id: number; | |
} | |
export interface FooModel extends Model { | |
name: string; | |
} | |
export interface BarModel extends Model { | |
name: string; | |
foo: FooModel; | |
foos: FooModel[]; | |
} | |
export type UnsavedModel<T extends Model> = Omit<T, 'id'> & { id?: number }; | |
export const isSaved = <T extends Model>(t: UnsavedModel<T>): t is T => typeof t.id === 'number'; | |
export type ConvertModelPropertiesTo<T extends Model, P, K extends keyof T = keyof T> = { | |
[p in K]: T[p] extends Model[] ? P[] : T[p] extends Model ? P : T[p]; | |
}; | |
/** | |
* Converts every or the selected Model like objects to a `number` | |
* or `number[]` to represent unresolved relative Models | |
*/ | |
export type FlatModel<T extends Model, K extends keyof T = keyof T> = | |
| ConvertModelPropertiesTo<T, number, K> | |
| Omit<T, K>; | |
const bar: BarModel = { foo: { id: 1, name: '' }, id: 1, name: '', foos: [] }; | |
const bar2: FlatModel<BarModel, 'foo'> = { foo: 1, foos: [], id: 2, name: '' }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment