Skip to content

Instantly share code, notes, and snippets.

@audunolsen
Created March 10, 2023 00:19
Show Gist options
  • Save audunolsen/30e5cf6028b289a5d01e54949a055339 to your computer and use it in GitHub Desktop.
Save audunolsen/30e5cf6028b289a5d01e54949a055339 to your computer and use it in GitHub Desktop.
import { HasKeys, IsEmpty, RequiredFields } from "."
export type OptionalIfEmpty<T> = [
...(IsEmpty<T> extends true
? [never?]
: HasKeys<RequiredFields<T>> extends true
? [T]
: [T?])
]
/**
* Wrap function signature to conditionally disallow
* last arg if its an empty object/interface OR allow
* omitting it if all fields are optional
*
* Doesn't properly infer Generics from wrapped function ?? :((
*/
export type FuncWithOptionalLastArg<Fn extends Function> = Fn extends (
...args: [...infer Params, infer LastParam]
) => infer Return
? (...args: [...Params, ...OptionalIfEmpty<LastParam>]) => Return
: never
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment