Skip to content

Instantly share code, notes, and snippets.

@minajevs
Last active October 15, 2018 14:21
Show Gist options
  • Save minajevs/8cc998c9ec08c1d8d81ba600fd53a726 to your computer and use it in GitHub Desktop.
Save minajevs/8cc998c9ec08c1d8d81ba600fd53a726 to your computer and use it in GitHub Desktop.
type OptionalSpread<T> =
T extends undefined
? []
: [T]
function foo<T = undefined>(...args: OptionalSpread<T>){
const arg = args[0] // Type of: T = undefined
if (arg === undefined)
doThis()
else
doThat(arg)
}
// number
foo<number>(42) // OK
foo<number>() // ERROR: 1 argument expected
foo<number>("bar") // ERROR: 'bar' is not assignable 'number'.
// undefined explicit
foo<undefined>() // OK Now is possible! Yay!
foo<undefined>(42) // ERROR: 0 arguments expected
foo<undefined>(undefined) // ERROR: 0 arguments expected Even more safety!
// undefined inferred
foo() // OK
foo(42) // OK single argument type is inferred, can't do anything about it
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment