Created
May 31, 2021 02:22
-
-
Save mendes5/66fda23c210dc93ced58af0397d4db89 to your computer and use it in GitHub Desktop.
Function used to make some fields of a object required, both at compile time and runtime. Throws exceptions https://www.typescriptlang.org/play?#code/MYewdgzgLgBAhhCBTATlAYgSyQGwCYQAKKSyYsAvDADwAqMSAHlEmATAEpKgp7XQpMYAOYAaGAFcwAazAgA7mAB84gKoNmrdtKQBPEADMYtJQAo8cKHABcx8Qez4It1QG0AugEpb9AGSckAEcJTBI+QkxgaTo1JSUYCniAbwAoFJgMmAMQFBhTHCRYB1w8GEMsxwJ…
This file contains hidden or 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
| const assertFieldsPresent = <T extends Record<string, unknown>, U extends keyof T>(data: T, fields: U[]): T & Required<Pick<T, U>> => { | |
| for (let field of fields) { | |
| const value = data[field]; | |
| if (value === undefined || value === null) { | |
| throw new Error(`[assertFields] Field "${field}" was not present`); | |
| } | |
| } | |
| // @ts-ignore; | |
| return data; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment