Last active
October 23, 2024 15:57
-
-
Save PhilomathJ/3ab10737bb7549cc5883b202191821e9 to your computer and use it in GitHub Desktop.
Typescript generic to modify every member of an interface without explicitly redefining each property. Useful in adhering to the DRY principle
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
| // Generic type to apply to every property modifying it as needed | |
| // In this case, we are making each property able to be undefined as well | |
| type AllowUndefined<T> = { [K in keyof T]: T[K] | undefined } | |
| // Initial interface | |
| interface Interface { | |
| a: number | |
| b: string | |
| } | |
| // Create new modified type from initial interface | |
| type InterfaceOrUndefined = AllowUndefined<Interface> | |
| // Test case 1 | |
| const i: InterfaceOrUndefined = { | |
| a: undefined, | |
| b: undefined, | |
| } | |
| // Test case 2 | |
| const j: InterfaceOrUndefined = { | |
| a: 456, | |
| b: undefined | |
| } | |
| // Test case 2 | |
| const k: InterfaceOrUndefined = { | |
| a: undefined, | |
| b: "abc" | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment