Skip to content

Instantly share code, notes, and snippets.

@dmwyatt
Created April 12, 2021 20:30
Show Gist options
  • Save dmwyatt/e1fa404c6682eaaa37b2293ab0685ae3 to your computer and use it in GitHub Desktop.
Save dmwyatt/e1fa404c6682eaaa37b2293ab0685ae3 to your computer and use it in GitHub Desktop.
[RequireAtLeastOne] Type that requires at least one of it's properties #types
// https://stackoverflow.com/a/49725198/23972
export type RequireAtLeastOne<T, Keys extends keyof T = keyof T> = Pick<
T,
Exclude<keyof T, Keys>
> &
{
[K in Keys]-?: Required<Pick<T, K>> & Partial<Pick<T, Exclude<Keys, K>>>;
}[Keys];
// Example usage that requires at least one of bar or baz
type Foo = RequireAtLeastOne<
{
bar?: string
baz?: number
somethingElse: Date
whatever: boolean
},
"bar" | "baz"
>;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment