Skip to content

Instantly share code, notes, and snippets.

@PhilomathJ
Last active October 23, 2024 15:57
Show Gist options
  • Select an option

  • Save PhilomathJ/3ab10737bb7549cc5883b202191821e9 to your computer and use it in GitHub Desktop.

Select an option

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
// 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